diff --git a/.github/workflows/config.yml b/.github/workflows/config.yml deleted file mode 100644 index 5826a7784..000000000 --- a/.github/workflows/config.yml +++ /dev/null @@ -1,76 +0,0 @@ -name: CI - -on: - push: - pull_request: - # Run weekly at 00:00 on Sunday. - schedule: - - cron: '0 0 * * 0' - -jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - max-parallel: 4 - matrix: - os: [ubuntu-latest, windows-latest] - python-version: ["3.9", "3.10", "3.11"] - - steps: - - uses: actions/checkout@v1 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v1 - with: - python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - python -m pip install --upgrade pip - python -m pip install -r requirements/development.txt - - name: Run tests - run: | - python -m pip install coverage - coverage run --source=axelrod -m unittest discover - - name: Report coverage - run: | - coverage report -m --fail-under=100 - - name: Check that documentation builds - run: | - python -m pip install sphinx - python -m pip install sphinx_rtd_theme - python -m pip install mock - python -m pip install numpy - cd docs; make clean; make html; cd ..; - - name: Run doctests - run: | - python doctests.py - - name: Check that all strategies are indexed - run: | - python run_strategy_indexer.py - - name: Check that strategies are added to axelrod.all_strategies - run: | - python -m pip install pylint - python -m pylint --disable=all --enable=unused-import axelrod/strategies/_strategies.py - - name: Check that installs - run: | - python setup.py install - cd .. - python -c "import axelrod" - - format-check: - needs: build - runs-on: ${{ matrix.os }} - strategy: - max-parallel: 4 - matrix: - os: [ubuntu-latest] - python-version: ["3.11"] - steps: - - name: Check imports are sorted - run: | - python -m pip install "isort==4.3.21" - python -m isort --check-only --recursive axelrod/. - - name: Check format - run: | - python -m pip install black=="22.10.0" - python -m black -l 80 . --check - diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 000000000..92c740362 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,31 @@ +name: CI + +on: [push, pull_request] + +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + max-parallel: 4 + matrix: + os: [ubuntu-latest, macOS-latest, windows-latest] + python-version: ["3.11", "3.12"] + + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + + - name: update pip + run: | + python -m pip install --upgrade pip + + - name: install tox + run: | + python -m pip install tox tox-gh-actions + + - name: run tox + run: | + python -m tox diff --git a/axelrod/classifier.py b/axelrod/classifier.py index 44edf510c..b9386099c 100644 --- a/axelrod/classifier.py +++ b/axelrod/classifier.py @@ -14,6 +14,7 @@ ) import yaml + from axelrod.makes_use_of import makes_use_of from axelrod.player import Player diff --git a/axelrod/fingerprint.py b/axelrod/fingerprint.py index 69e880cbf..dec12ae05 100644 --- a/axelrod/fingerprint.py +++ b/axelrod/fingerprint.py @@ -3,18 +3,19 @@ from tempfile import mkstemp from typing import Any, List, Union -import axelrod as axl import dask.dataframe as dd import matplotlib.pyplot as plt import numpy as np import tqdm +from mpl_toolkits.axes_grid1 import make_axes_locatable + +import axelrod as axl from axelrod import Player from axelrod.interaction_utils import ( compute_final_score_per_turn, read_interactions_from_file, ) from axelrod.strategy_transformers import DualTransformer, JossAnnTransformer -from mpl_toolkits.axes_grid1 import make_axes_locatable Point = namedtuple("Point", "x y") diff --git a/axelrod/game.py b/axelrod/game.py index 6b95bbbf3..0d8f94380 100644 --- a/axelrod/game.py +++ b/axelrod/game.py @@ -1,5 +1,5 @@ -from typing import Tuple, Union from enum import Enum +from typing import Tuple, Union import numpy as np @@ -71,6 +71,7 @@ def get_value(x): if isinstance(x, Enum): return x.value return x + row, col = map(get_value, pair) return (self.A[row][col], self.B[row][col]) @@ -97,7 +98,9 @@ class Game(AsymmetricGame): The numerical score attribute to all combinations of action pairs. """ - def __init__(self, r: Score = 3, s: Score = 0, t: Score = 5, p: Score = 1) -> None: + def __init__( + self, r: Score = 3, s: Score = 0, t: Score = 5, p: Score = 1 + ) -> None: """Create a new game object. Parameters diff --git a/axelrod/interaction_utils.py b/axelrod/interaction_utils.py index 220053ee3..b255893a5 100644 --- a/axelrod/interaction_utils.py +++ b/axelrod/interaction_utils.py @@ -7,10 +7,12 @@ This is used by both the Match class and the ResultSet class which analyse interactions. """ + from collections import Counter, defaultdict import pandas as pd import tqdm + from axelrod.action import Action, str_to_actions from .game import Game diff --git a/axelrod/load_data_.py b/axelrod/load_data_.py index cae4d2d4a..e55f5f395 100644 --- a/axelrod/load_data_.py +++ b/axelrod/load_data_.py @@ -1,7 +1,7 @@ import pathlib +import pkgutil from typing import Dict, List, Text, Tuple -import pkgutil def axl_filename(path: pathlib.Path) -> pathlib.Path: """Given a path under Axelrod/, return absolute filepath. @@ -27,7 +27,7 @@ def load_file(filename: str, directory: str) -> List[List[str]]: path = str(pathlib.Path(directory) / filename) data_bytes = pkgutil.get_data(__name__, path) data = data_bytes.decode("UTF-8", "replace") - + rows = [] for line in data.split("\n"): if line.startswith("#") or len(line) == 0: @@ -57,7 +57,12 @@ def load_pso_tables(filename="pso_gambler.csv", directory="data"): rows = load_file(filename, directory) d = dict() for row in rows: - name, a, b, c, = ( + ( + name, + a, + b, + c, + ) = ( str(row[0]), int(row[1]), int(row[2]), diff --git a/axelrod/moran.py b/axelrod/moran.py index 6f48ed07d..b5e3ffbe8 100644 --- a/axelrod/moran.py +++ b/axelrod/moran.py @@ -5,6 +5,7 @@ import matplotlib.pyplot as plt import numpy as np + from axelrod import DEFAULT_TURNS, EvolvablePlayer, Game, Player from axelrod.deterministic_cache import DeterministicCache from axelrod.graph import Graph, complete_graph diff --git a/axelrod/player.py b/axelrod/player.py index 87c08ddb8..fe1e981ec 100644 --- a/axelrod/player.py +++ b/axelrod/player.py @@ -6,6 +6,7 @@ from typing import Any, Dict import numpy as np + from axelrod import _module_random from axelrod.action import Action from axelrod.game import DefaultGame @@ -121,7 +122,7 @@ def _post_init(self): def _post_transform(self): """Handles post transform tasks such as further reclassifying.""" # Reclassify strategy post __init__, if needed. - for (reclassifier, args, kwargs) in self._reclassifiers: + for reclassifier, args, kwargs in self._reclassifiers: self.classifier = reclassifier(self.classifier, *args, **kwargs) def __eq__(self, other): diff --git a/axelrod/plot.py b/axelrod/plot.py index 0e0fcc30a..48509a1c7 100644 --- a/axelrod/plot.py +++ b/axelrod/plot.py @@ -176,7 +176,7 @@ def _payoff_heatmap( names: namesType, title: titleType = None, ax: matplotlib.axes.SubplotBase = None, - cmap: str = 'viridis' + cmap: str = "viridis", ) -> matplotlib.figure.Figure: """Generic heatmap plot""" diff --git a/axelrod/random_.py b/axelrod/random_.py index bafb84a5a..69c1a9fbc 100644 --- a/axelrod/random_.py +++ b/axelrod/random_.py @@ -1,9 +1,10 @@ from typing import Optional import numpy as np -from axelrod.action import Action from numpy.random import RandomState +from axelrod.action import Action + C, D = Action.C, Action.D diff --git a/axelrod/result_set.py b/axelrod/result_set.py index 5f1fc8d8a..db5921c7b 100644 --- a/axelrod/result_set.py +++ b/axelrod/result_set.py @@ -9,6 +9,7 @@ import dask.dataframe as dd import numpy as np import tqdm + from axelrod.action import Action from . import eigen diff --git a/axelrod/strategies/_strategies.py b/axelrod/strategies/_strategies.py index 92dafc523..b1f147993 100644 --- a/axelrod/strategies/_strategies.py +++ b/axelrod/strategies/_strategies.py @@ -20,6 +20,7 @@ ) # isort:skip_file """ + import warnings from .adaptive import Adaptive @@ -152,16 +153,6 @@ from .hmm import EvolvedHMM5 from .hmm import EvolvableHMMPlayer, HMMPlayer # pylint: disable=unused-import -try: - from .human import Human # pylint: disable=unused-import -except ImportError as ie: # pragma: no cover - # Check that the expected module is missing and no other. - if ie.name == "prompt_toolkit": - warnings.warn( - "Human strategy not available because python package prompt_toolkit is not available." - ) - else: - raise ie from .hunter import ( AlternatorHunter, CooperatorHunter, diff --git a/axelrod/strategies/adaptor.py b/axelrod/strategies/adaptor.py index f949f0afe..98d5f73f3 100644 --- a/axelrod/strategies/adaptor.py +++ b/axelrod/strategies/adaptor.py @@ -1,8 +1,9 @@ from typing import Dict, Tuple +from numpy import heaviside + from axelrod.action import Action from axelrod.player import Player -from numpy import heaviside C, D = Action.C, Action.D diff --git a/axelrod/strategies/ann.py b/axelrod/strategies/ann.py index e838ec09e..e7956450f 100644 --- a/axelrod/strategies/ann.py +++ b/axelrod/strategies/ann.py @@ -1,6 +1,7 @@ from typing import List, Tuple import numpy as np + from axelrod.action import Action from axelrod.evolvable_player import ( EvolvablePlayer, diff --git a/axelrod/strategies/axelrod_first.py b/axelrod/strategies/axelrod_first.py index a80ae3397..8ab082f84 100644 --- a/axelrod/strategies/axelrod_first.py +++ b/axelrod/strategies/axelrod_first.py @@ -15,10 +15,11 @@ from typing import Dict, List, Optional, Tuple +from scipy.stats import chisquare + from axelrod.action import Action from axelrod.player import Player from axelrod.strategy_transformers import FinalTransformer -from scipy.stats import chisquare from .memoryone import MemoryOnePlayer @@ -624,7 +625,6 @@ def score_history( opponent_history: List[Action], score_map: Dict[Tuple[Action, Action], int], ) -> int: - """Implements the Nydegger formula A = 16 a_1 + 4 a_2 + a_3""" a = 0 for i, weight in [(-1, 16), (-2, 4), (-3, 1)]: diff --git a/axelrod/strategies/axelrod_second.py b/axelrod/strategies/axelrod_second.py index 480e589bd..784eb90d2 100644 --- a/axelrod/strategies/axelrod_second.py +++ b/axelrod/strategies/axelrod_second.py @@ -7,6 +7,7 @@ from typing import List import numpy as np + from axelrod.action import Action from axelrod.interaction_utils import compute_final_score from axelrod.player import Player @@ -204,7 +205,6 @@ def strategy(self, opponent: Player) -> Action: class SecondByTranquilizer(Player): - """ Submitted to Axelrod's second tournament by Craig Feathers @@ -341,7 +341,6 @@ def __init__(self): self.dict = {C: 0, D: 1} def update_state(self, opponent): - """ Calculates the ratio values for the one_turn_after_good_defection_ratio, two_turns_after_good_defection_ratio and the probability values, @@ -1349,9 +1348,9 @@ def strategy(self, opponent: Player) -> Action: if self.detect_streak(opponent.history[-1]): return self.try_return(D, inc_parity=True) if self.detect_parity_streak(opponent.history[-1]): - self.parity_streak[ - self.parity_bit - ] = 0 # Reset `parity_streak` when we hit the limit. + self.parity_streak[self.parity_bit] = ( + 0 # Reset `parity_streak` when we hit the limit. + ) self.parity_hits += ( 1 # Keep track of how many times we hit the limit. ) diff --git a/axelrod/strategies/darwin.py b/axelrod/strategies/darwin.py index bac573092..6ae231cd2 100644 --- a/axelrod/strategies/darwin.py +++ b/axelrod/strategies/darwin.py @@ -3,6 +3,7 @@ indicated by their classifier). We do not recommend putting a lot of time in to optimising it. """ + from typing import Optional from axelrod.action import Action diff --git a/axelrod/strategies/gambler.py b/axelrod/strategies/gambler.py index 4260aa40f..c686cc2fe 100644 --- a/axelrod/strategies/gambler.py +++ b/axelrod/strategies/gambler.py @@ -4,6 +4,7 @@ For the original see: https://gist.github.com/GDKO/60c3d0fd423598f3c4e4 """ + from typing import Any from axelrod.action import Action, actions_to_str, str_to_actions diff --git a/axelrod/strategies/human.py b/axelrod/strategies/human.py deleted file mode 100644 index 190590c12..000000000 --- a/axelrod/strategies/human.py +++ /dev/null @@ -1,182 +0,0 @@ -from os import linesep - -from axelrod.action import Action -from axelrod.player import Player -from prompt_toolkit import prompt -from prompt_toolkit.validation import ValidationError, Validator - -try: # pragma: no cover - from prompt_toolkit.styles import style_from_dict - from prompt_toolkit.token import Token - - token_toolbar = Token.Toolbar - bottom_toolbar_name = "get_bottom_toolbar_tokens" - PROMPT2 = False - -except ImportError: # prompt_toolkit v2 - from prompt_toolkit.styles import Style - - style_from_dict = Style.from_dict - token_toolbar = "pygments.toolbar" - bottom_toolbar_name = "bottom_toolbar" - PROMPT2 = True - -C, D = Action.C, Action.D - -toolbar_style = style_from_dict({token_toolbar: "#ffffff bg:#333333"}) - - -class ActionValidator(Validator): - """ - A class to validate input from prompt_toolkit.prompt - Described at http://python-prompt-toolkit.readthedocs.io/en/latest/pages/building_prompts.html#input-validation - """ - - def validate(self, document) -> None: - text = document.text - - if text and text.upper() not in ["C", "D"]: - raise ValidationError( - message="Action must be C or D", cursor_position=0 - ) - - -class Human(Player): - """ - A strategy that prompts for keyboard input rather than deriving its own - action. - - This strategy is intended to be used interactively by a user playing - against other strategies from within the rest of the library. Unlike - other strategies, it is designed to be a teaching aid rather than a - research tool. - """ - - name = "Human" - classifier = { - "memory_depth": float("inf"), - "stochastic": True, - "long_run_time": True, - "inspects_source": True, - "manipulates_source": False, - "manipulates_state": False, - } - - def __init__(self, name="human", c_symbol="C", d_symbol="D"): - """ - Parameters - ---------- - name: string - The name of the human player - c_symbol: string - A symbol to denote cooperation within the history toolbar - and prompt - d_symbol: string - A symbol to denote defection within the history toolbar - and prompt - """ - super().__init__() - self.human_name = name - self.symbols = {C: c_symbol, D: d_symbol} - - def _history_toolbar(self): - """ - A prompt-toolkit function to define the bottom toolbar. - Described at http://python-prompt-toolkit.readthedocs.io/en/latest/pages/building_prompts.html#adding-a-bottom-toolbar - """ - my_history = [self.symbols[action] for action in self.history] - opponent_history = [ - self.symbols[action] for action in self.history.coplays - ] - history = list(zip(my_history, opponent_history)) - if self.history: - content = "History ({}, opponent): {}".format( - self.human_name, history - ) - else: - content = "" - return content - - def _status_messages(self): - """ - A method to define the messages printed to the console and - displayed in the prompt-toolkit bottom toolbar. - - The bottom toolbar is defined only if a match is in progress. - - The console print statement is either the result of the previous - turn or a message indicating that new match is starting. - - Returns - ------- - dict - mapping print or toolbar to the relevant string - """ - if self.history: - toolbar = ( - self._history_toolbar - if PROMPT2 - else lambda cli: [(token_toolbar, self._history_toolbar())] - ) - print_statement = ( - "{}Turn {}: {} played {}, opponent played {}".format( - linesep, - len(self.history), - self.human_name, - self.symbols[self.history[-1]], - self.symbols[self.history.coplays[-1]], - ) - ) - else: - toolbar = None - print_statement = "{}Starting new match".format(linesep) - - return {"toolbar": toolbar, "print": print_statement} - - def _get_human_input(self) -> Action: # pragma: no cover - """ - A method to prompt the user for input, validate it and display - the bottom toolbar. - - Returns - ------- - string - Uppercase C or D indicating the action to play - """ - action = prompt( - "Turn {} action [C or D] for {}: ".format( - len(self.history) + 1, self.human_name - ), - validator=ActionValidator(), - style=toolbar_style, - **{bottom_toolbar_name: self.status_messages["toolbar"]}, - ) - - return Action.from_char(action.upper()) - - def strategy(self, opponent: Player, input_function=None): - """ - Ordinarily, the strategy prompts for keyboard input rather than - deriving its own action. - - However, it is also possible to pass a function which returns a valid - action. This is mainly used for testing purposes in order to by-pass - the need for human interaction. - """ - - self.status_messages = self._status_messages() - self.status_messages = self._status_messages() - print(self.status_messages["print"]) - - if not input_function: # pragma: no cover - action = self._get_human_input() - else: - action = input_function() - - return action - - def __repr__(self): - """ - Override the default __repr__ of the class - """ - return "Human: {}".format(self.human_name) diff --git a/axelrod/strategies/meta.py b/axelrod/strategies/meta.py index d1e496254..473f7f31e 100644 --- a/axelrod/strategies/meta.py +++ b/axelrod/strategies/meta.py @@ -1,4 +1,5 @@ import numpy as np + from axelrod.action import Action from axelrod.classifier import Classifiers from axelrod.player import Player diff --git a/axelrod/strategies/revised_downing.py b/axelrod/strategies/revised_downing.py index f9b1e47b1..a4cedeb93 100644 --- a/axelrod/strategies/revised_downing.py +++ b/axelrod/strategies/revised_downing.py @@ -2,6 +2,7 @@ Revised Downing implemented from the Fortran source code for the second of Axelrod's tournaments. """ + from axelrod.action import Action from axelrod.player import Player diff --git a/axelrod/strategies/titfortat.py b/axelrod/strategies/titfortat.py index e98a8aadf..dbeba4b9e 100644 --- a/axelrod/strategies/titfortat.py +++ b/axelrod/strategies/titfortat.py @@ -945,7 +945,7 @@ def strategy(self, opponent): if not opponent.history: # Make sure we cooperate first turn return C - # BBE modification + # BBE modification if opponent.history[-1] == C: # Cooperate with 0.9 return self._random.random_choice(0.9) diff --git a/axelrod/strategy_transformers.py b/axelrod/strategy_transformers.py index 70773ff60..6be839f95 100644 --- a/axelrod/strategy_transformers.py +++ b/axelrod/strategy_transformers.py @@ -133,7 +133,8 @@ def inner_strategy(self, opponent): def dual_inner_strategy(self, opponent): """The dual wrapper requires flipping the history. It may be more efficient - to use a custom History class that tracks a flipped history and swaps labels.""" + to use a custom History class that tracks a flipped history and swaps labels. + """ self._history = self.history.flip_plays() proposed_action = inner_strategy(self, opponent) self._history = self.history.flip_plays() diff --git a/axelrod/tests/integration/test_filtering.py b/axelrod/tests/integration/test_filtering.py index d2b64f99c..0a5edcf51 100644 --- a/axelrod/tests/integration/test_filtering.py +++ b/axelrod/tests/integration/test_filtering.py @@ -1,11 +1,12 @@ import unittest import warnings -import axelrod as axl -from axelrod.tests.property import strategy_lists from hypothesis import example, given, settings from hypothesis.strategies import integers, lists, sampled_from +import axelrod as axl +from axelrod.tests.property import strategy_lists + def classifiers_lists(min_size=1, max_size=5): """ diff --git a/axelrod/tests/integration/test_matches.py b/axelrod/tests/integration/test_matches.py index 46f4e318f..d3912de69 100644 --- a/axelrod/tests/integration/test_matches.py +++ b/axelrod/tests/integration/test_matches.py @@ -1,11 +1,13 @@ """Tests for some expected match behaviours""" + import unittest -import axelrod as axl -from axelrod.tests.property import strategy_lists from hypothesis import given, settings from hypothesis.strategies import integers +import axelrod as axl +from axelrod.tests.property import strategy_lists + C, D = axl.Action.C, axl.Action.D deterministic_strategies = [ diff --git a/axelrod/tests/integration/test_tournament.py b/axelrod/tests/integration/test_tournament.py index 8568e165d..36329c511 100644 --- a/axelrod/tests/integration/test_tournament.py +++ b/axelrod/tests/integration/test_tournament.py @@ -2,11 +2,12 @@ import pathlib import unittest +from hypothesis import given, settings + import axelrod as axl from axelrod.load_data_ import axl_filename from axelrod.strategy_transformers import FinalTransformer from axelrod.tests.property import tournaments -from hypothesis import given, settings class TestTournament(unittest.TestCase): diff --git a/axelrod/tests/property.py b/axelrod/tests/property.py index 21648fac8..263d1749c 100644 --- a/axelrod/tests/property.py +++ b/axelrod/tests/property.py @@ -1,9 +1,10 @@ """ A module for creating hypothesis based strategies for property based testing """ + import itertools -import axelrod as axl +from hypothesis.extra.numpy import arrays from hypothesis.strategies import ( composite, floats, @@ -11,7 +12,8 @@ lists, sampled_from, ) -from hypothesis.extra.numpy import arrays + +import axelrod as axl @composite @@ -394,4 +396,4 @@ def asymmetric_games(draw, valid=True): A = draw(arrays(int, (rows, cols))) B = draw(arrays(int, (cols, rows))) - return axl.AsymmetricGame(A, B) \ No newline at end of file + return axl.AsymmetricGame(A, B) diff --git a/axelrod/tests/strategies/test_ann.py b/axelrod/tests/strategies/test_ann.py index c2a8290fe..3a308bf46 100644 --- a/axelrod/tests/strategies/test_ann.py +++ b/axelrod/tests/strategies/test_ann.py @@ -1,4 +1,5 @@ """Tests for the ANN strategy.""" + import unittest import axelrod as axl diff --git a/axelrod/tests/strategies/test_cycler.py b/axelrod/tests/strategies/test_cycler.py index 7e3e7e230..fe94bf29b 100644 --- a/axelrod/tests/strategies/test_cycler.py +++ b/axelrod/tests/strategies/test_cycler.py @@ -1,7 +1,10 @@ """Tests for the Cycler strategies.""" + import itertools import unittest +import pytest + import axelrod as axl from axelrod._strategy_utils import detect_cycle from axelrod.action import Action, str_to_actions @@ -106,6 +109,7 @@ def test_cycle_raises_value_error_on_bad_cycle_str(self): self.assertRaises(ValueError, axl.Cycler, cycle="CdDC") +@pytest.mark.skip(reason="This is a function used to test other strategies.") def test_cycler_factory(cycle_str): class TestCyclerChild(TestPlayer): diff --git a/axelrod/tests/strategies/test_finite_state_machines.py b/axelrod/tests/strategies/test_finite_state_machines.py index 10eb34ab1..487abc8bf 100644 --- a/axelrod/tests/strategies/test_finite_state_machines.py +++ b/axelrod/tests/strategies/test_finite_state_machines.py @@ -1,4 +1,5 @@ """Tests for Finite State Machine Strategies.""" + import unittest import axelrod as axl diff --git a/axelrod/tests/strategies/test_gambler.py b/axelrod/tests/strategies/test_gambler.py index 8683f9294..62810b7a1 100755 --- a/axelrod/tests/strategies/test_gambler.py +++ b/axelrod/tests/strategies/test_gambler.py @@ -1,5 +1,6 @@ """Test for the Gambler strategy. Most tests come from the LookerUp test suite. """ + import copy import unittest @@ -529,7 +530,7 @@ def test_receive_vector(self): self.assertRaises( AttributeError, axl.EvolvableGambler.__getattribute__, - *[player, "vector"] + *[player, "vector"], ) vector = [random.random() for _ in range(8)] diff --git a/axelrod/tests/strategies/test_hmm.py b/axelrod/tests/strategies/test_hmm.py index 4941ed53e..0e2539f9a 100644 --- a/axelrod/tests/strategies/test_hmm.py +++ b/axelrod/tests/strategies/test_hmm.py @@ -1,4 +1,5 @@ """Tests for Hidden Markov Model Strategies.""" + import unittest import axelrod as axl diff --git a/axelrod/tests/strategies/test_human.py b/axelrod/tests/strategies/test_human.py deleted file mode 100644 index ffe35f5d0..000000000 --- a/axelrod/tests/strategies/test_human.py +++ /dev/null @@ -1,134 +0,0 @@ -from os import linesep -from unittest import TestCase -from unittest.mock import patch - -import axelrod as axl -from axelrod.strategies.human import ActionValidator, Human -from prompt_toolkit.validation import ValidationError - -from .test_player import TestPlayer - -C, D = axl.Action.C, axl.Action.D - - -class TestDocument(object): - """ - A class to mimic a prompt-toolkit document having just the text attribute. - """ - - def __init__(self, text): - self.text = text - - -class TestActionValidator(TestCase): - def test_validator(self): - test_documents = [TestDocument(x) for x in ["C", "c", "D", "d"]] - for test_document in test_documents: - ActionValidator().validate(test_document) - - test_document = TestDocument("E") - self.assertRaises( - ValidationError, ActionValidator().validate, test_document - ) - - -class TestHumanClass(TestPlayer): - - name = "Human: human, C, D" - player = Human - expected_classifier = { - "memory_depth": float("inf"), - "stochastic": True, - "makes_use_of": set(), - "long_run_time": True, - "inspects_source": True, - "manipulates_source": False, - "manipulates_state": False, - } - - def test_init(self): - human = Human(name="test human", c_symbol="X", d_symbol="Y") - self.assertEqual(human.human_name, "test human") - self.assertEqual(human.symbols, {C: "X", D: "Y"}) - - def test_history_toolbar(self): - human = Human() - expected_content = "" - actual_content = human._history_toolbar() - self.assertEqual(actual_content, expected_content) - - human.history.append(C, C) - expected_content = "History (human, opponent): [('C', 'C')]" - actual_content = human._history_toolbar() - self.assertIn(actual_content, expected_content) - - def test_status_messages(self): - human = Human() - expected_messages = { - "toolbar": None, - "print": "{}Starting new match".format(linesep), - } - actual_messages = human._status_messages() - self.assertEqual(actual_messages, expected_messages) - - human.history.append(C, C) - expected_print_message = ( - "{}Turn 1: human played C, opponent played C".format(linesep) - ) - actual_messages = human._status_messages() - self.assertEqual(actual_messages["print"], expected_print_message) - self.assertIsNotNone(actual_messages["toolbar"]) - - def test_get_human_input_c(self): - with patch("axelrod.human.prompt", return_value="c") as prompt_: - actions = [(C, C)] * 5 - self.versus_test(axl.Cooperator(), expected_actions=actions) - self.assertEqual( - prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) - ) - - def test_get_human_input_C(self): - with patch("axelrod.human.prompt", return_value="C") as prompt_: - actions = [(C, C)] * 5 - self.versus_test(axl.Cooperator(), expected_actions=actions) - self.assertEqual( - prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) - ) - - def test_get_human_input_d(self): - with patch("axelrod.human.prompt", return_value="d") as prompt_: - actions = [(D, C)] * 5 - self.versus_test(axl.Cooperator(), expected_actions=actions) - self.assertEqual( - prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) - ) - - def test_get_human_input_D(self): - with patch("axelrod.human.prompt", return_value="D") as prompt_: - actions = [(D, C)] * 5 - self.versus_test(axl.Cooperator(), expected_actions=actions) - self.assertEqual( - prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",) - ) - - def test_strategy(self): - human = Human() - expected_action = C - actual_action = human.strategy(axl.Player(), lambda: C) - self.assertEqual(actual_action, expected_action) - - def test_reset_history_and_attributes(self): - """Overwrite the reset method for this strategy.""" - pass - - def test_repr(self): - human = Human() - self.assertEqual(human.__repr__(), "Human: human") - - human = Human(name="John Nash") - self.assertEqual(human.__repr__(), "Human: John Nash") - human = Human(name="John Nash", c_symbol="1", d_symbol="2") - self.assertEqual(human.__repr__(), "Human: John Nash") - - def equality_of_players_test(self, p1, p2, seed, opponent): - return True diff --git a/axelrod/tests/strategies/test_hunter.py b/axelrod/tests/strategies/test_hunter.py index 60a377a07..08745f270 100644 --- a/axelrod/tests/strategies/test_hunter.py +++ b/axelrod/tests/strategies/test_hunter.py @@ -1,4 +1,5 @@ """Tests for the Hunter strategy.""" + import unittest import axelrod as axl diff --git a/axelrod/tests/strategies/test_memoryone.py b/axelrod/tests/strategies/test_memoryone.py index 2c7e46df6..4ae9d9340 100644 --- a/axelrod/tests/strategies/test_memoryone.py +++ b/axelrod/tests/strategies/test_memoryone.py @@ -1,4 +1,5 @@ """Tests for the Memoryone strategies.""" + import unittest import warnings diff --git a/axelrod/tests/strategies/test_meta.py b/axelrod/tests/strategies/test_meta.py index 1aa2ff704..2e606f82c 100644 --- a/axelrod/tests/strategies/test_meta.py +++ b/axelrod/tests/strategies/test_meta.py @@ -1,10 +1,11 @@ """Tests for the various Meta strategies.""" +from hypothesis import HealthCheck, given, settings +from hypothesis.strategies import integers + import axelrod as axl from axelrod.classifier import Classifiers from axelrod.tests.property import strategy_lists -from hypothesis import given, settings -from hypothesis.strategies import integers from .test_player import TestPlayer @@ -67,7 +68,11 @@ def test_repr(self): ) @given(seed=integers(min_value=1, max_value=20000000)) - @settings(max_examples=1, deadline=None) + @settings( + max_examples=1, + deadline=None, + suppress_health_check=(HealthCheck.differing_executors,), + ) def test_clone(self, seed): # Test that the cloned player produces identical play player1 = self.player() @@ -97,8 +102,12 @@ def test_update_histories(self): with self.assertRaises(TypeError): p.update_histories(C) - @settings(max_examples=5, deadline=None) @given(opponent_list=strategy_lists(max_size=1)) + @settings( + max_examples=5, + deadline=None, + suppress_health_check=(HealthCheck.differing_executors,), + ) def test_players_return_valid_actions(self, opponent_list): """ Whenever a new strategy is added to the library this potentially diff --git a/axelrod/tests/strategies/test_player.py b/axelrod/tests/strategies/test_player.py index de23ffa9d..1d549209b 100644 --- a/axelrod/tests/strategies/test_player.py +++ b/axelrod/tests/strategies/test_player.py @@ -4,12 +4,14 @@ import unittest import warnings -import axelrod as axl import numpy as np -from axelrod.tests.property import strategy_lists -from hypothesis import given, settings +import pytest +from hypothesis import HealthCheck, given, settings from hypothesis.strategies import integers, sampled_from +import axelrod as axl +from axelrod.tests.property import strategy_lists + C, D = axl.Action.C, axl.Action.D random = axl.RandomGenerator() short_run_time_short_mem = [ @@ -420,7 +422,11 @@ def equality_of_players_test(self, p1, p2, seed, opponent): opponent=sampled_from(short_run_time_short_mem), seed=integers(min_value=1, max_value=200), ) - @settings(max_examples=1, deadline=None) + @settings( + max_examples=1, + deadline=None, + suppress_health_check=(HealthCheck.differing_executors,), + ) def test_equality_of_clone(self, seed, opponent): p1 = self.player() p2 = p1.clone() @@ -430,7 +436,11 @@ def test_equality_of_clone(self, seed, opponent): opponent=sampled_from(axl.short_run_time_strategies), seed=integers(min_value=1, max_value=200), ) - @settings(max_examples=1, deadline=None) + @settings( + max_examples=1, + deadline=None, + suppress_health_check=(HealthCheck.differing_executors,), + ) def test_equality_of_pickle_clone(self, seed, opponent): p1 = self.player() p2 = pickle.loads(pickle.dumps(p1)) @@ -463,7 +473,11 @@ def test_reset_clone(self): turns=integers(min_value=5, max_value=10), noise=integers(min_value=0, max_value=10), ) - @settings(max_examples=1, deadline=None) + @settings( + max_examples=1, + deadline=None, + suppress_health_check=(HealthCheck.differing_executors,), + ) def test_clone_reproducible_play(self, seed, turns, noise): # Test that the cloned player produces identical play player = self.player() @@ -503,7 +517,11 @@ def test_clone_reproducible_play(self, seed, turns, noise): seed=integers(min_value=1, max_value=200), turns=integers(min_value=1, max_value=200), ) - @settings(max_examples=1, deadline=None) + @settings( + max_examples=1, + deadline=None, + suppress_health_check=(HealthCheck.differing_executors,), + ) def test_memory_depth_upper_bound(self, strategies, seed, turns): """ Test that the memory depth is indeed an upper bound. @@ -699,6 +717,7 @@ def test_versus_with_incorrect_history_lengths(self): self.versus_test(p1, p2, actions1, actions2) +@pytest.mark.skip(reason="This is a function used to test other strategies.") def test_four_vector(test_class, expected_dictionary): """ Checks that two dictionaries match -- the four-vector defining @@ -711,6 +730,7 @@ def test_four_vector(test_class, expected_dictionary): ) +@pytest.mark.skip(reason="This is a function used to test other strategies.") def test_memory(player, opponent, memory_length, seed=0, turns=10): """ Checks if a player reacts to the plays of an opponent in the same way if diff --git a/axelrod/tests/strategies/test_sequence_player.py b/axelrod/tests/strategies/test_sequence_player.py index 2a3c655ef..8661b38b9 100644 --- a/axelrod/tests/strategies/test_sequence_player.py +++ b/axelrod/tests/strategies/test_sequence_player.py @@ -1,4 +1,5 @@ """Tests for the Thue-Morse strategies.""" + import unittest import axelrod as axl diff --git a/axelrod/tests/strategies/test_titfortat.py b/axelrod/tests/strategies/test_titfortat.py index 09d82b80f..17d46d091 100644 --- a/axelrod/tests/strategies/test_titfortat.py +++ b/axelrod/tests/strategies/test_titfortat.py @@ -1,11 +1,13 @@ """Tests for the tit for tat strategies.""" + import copy -import axelrod as axl -from axelrod.tests.property import strategy_lists from hypothesis import given, settings from hypothesis.strategies import integers +import axelrod as axl +from axelrod.tests.property import strategy_lists + from .test_player import TestPlayer C, D = axl.Action.C, axl.Action.D diff --git a/axelrod/tests/unit/test_classification.py b/axelrod/tests/unit/test_classification.py index 83f14ea4f..f66243b1a 100644 --- a/axelrod/tests/unit/test_classification.py +++ b/axelrod/tests/unit/test_classification.py @@ -5,8 +5,9 @@ import warnings from typing import Any, Text -import axelrod as axl import yaml + +import axelrod as axl from axelrod.classifier import ( Classifier, Classifiers, diff --git a/axelrod/tests/unit/test_eigen.py b/axelrod/tests/unit/test_eigen.py index 34a650f72..707ca38c0 100644 --- a/axelrod/tests/unit/test_eigen.py +++ b/axelrod/tests/unit/test_eigen.py @@ -3,9 +3,10 @@ import unittest import numpy as np -from axelrod.eigen import _normalise, principal_eigenvector from numpy.testing import assert_array_almost_equal +from axelrod.eigen import _normalise, principal_eigenvector + class FunctionCases(unittest.TestCase): def test_identity_matrices(self): diff --git a/axelrod/tests/unit/test_filters.py b/axelrod/tests/unit/test_filters.py index 70e11ed6e..d360890d8 100644 --- a/axelrod/tests/unit/test_filters.py +++ b/axelrod/tests/unit/test_filters.py @@ -1,10 +1,11 @@ import unittest +from hypothesis import example, given, settings +from hypothesis.strategies import integers + import axelrod as axl from axelrod.player import Player from axelrod.strategies._filters import * -from hypothesis import example, given, settings -from hypothesis.strategies import integers class TestFilters(unittest.TestCase): diff --git a/axelrod/tests/unit/test_fingerprint.py b/axelrod/tests/unit/test_fingerprint.py index 7660550cf..91392ec75 100644 --- a/axelrod/tests/unit/test_fingerprint.py +++ b/axelrod/tests/unit/test_fingerprint.py @@ -4,13 +4,14 @@ from tempfile import mkstemp from unittest.mock import patch -import axelrod as axl import matplotlib.pyplot import numpy as np +from hypothesis import given, settings + +import axelrod as axl from axelrod.fingerprint import AshlockFingerprint, Point, TransitiveFingerprint from axelrod.load_data_ import axl_filename from axelrod.tests.property import strategy_lists -from hypothesis import given, settings C, D = axl.Action.C, axl.Action.D diff --git a/axelrod/tests/unit/test_game.py b/axelrod/tests/unit/test_game.py index d97fa7b0a..083431e22 100644 --- a/axelrod/tests/unit/test_game.py +++ b/axelrod/tests/unit/test_game.py @@ -1,13 +1,12 @@ import unittest import numpy as np - -import axelrod as axl -from axelrod.tests.property import games, asymmetric_games from hypothesis import given, settings +from hypothesis.extra.numpy import array_shapes, arrays from hypothesis.strategies import integers -from hypothesis.extra.numpy import arrays, array_shapes +import axelrod as axl +from axelrod.tests.property import asymmetric_games, games C, D = axl.Action.C, axl.Action.D @@ -86,17 +85,20 @@ def test_random_repr(self, game): def test_integer_actions(self, game): """Test Actions and integers are treated equivalently.""" pair_ints = { - (C, C): (0 ,0), + (C, C): (0, 0), (C, D): (0, 1), (D, C): (1, 0), - (D, D): (1, 1) + (D, D): (1, 1), } for key, value in pair_ints.items(): self.assertEqual(game.score(key), game.score(value)) + class TestAsymmetricGame(unittest.TestCase): - @given(A=arrays(int, array_shapes(min_dims=2, max_dims=2, min_side=2)), - B=arrays(int, array_shapes(min_dims=2, max_dims=2, min_side=2))) + @given( + A=arrays(int, array_shapes(min_dims=2, max_dims=2, min_side=2)), + B=arrays(int, array_shapes(min_dims=2, max_dims=2, min_side=2)), + ) @settings(max_examples=5) def test_invalid_matrices(self, A, B): """Test that an error is raised when the matrices aren't the right size.""" @@ -114,17 +116,23 @@ def test_invalid_matrices(self, A, B): @settings(max_examples=5) def test_random_repr(self, asymgame): """Test repr with random scores.""" - expected_repr = "Axelrod game with matrices: {}".format((asymgame.A, asymgame.B)) + expected_repr = "Axelrod game with matrices: {}".format( + (asymgame.A, asymgame.B) + ) self.assertEqual(expected_repr, asymgame.__repr__()) self.assertEqual(expected_repr, str(asymgame)) - @given(asymgame1=asymmetric_games(), - asymgame2=asymmetric_games()) + @given(asymgame1=asymmetric_games(), asymgame2=asymmetric_games()) @settings(max_examples=5) def test_equality(self, asymgame1, asymgame2): """Tests equality of AsymmetricGames based on their matrices.""" - self.assertFalse(asymgame1=='foo') + self.assertFalse(asymgame1 == "foo") self.assertEqual(asymgame1, asymgame1) self.assertEqual(asymgame2, asymgame2) - self.assertEqual((asymgame1==asymgame2), (asymgame1.A.all() == asymgame2.A.all() - and asymgame1.B.all() == asymgame2.B.all())) \ No newline at end of file + self.assertEqual( + (asymgame1 == asymgame2), + ( + asymgame1.A.all() == asymgame2.A.all() + and asymgame1.B.all() == asymgame2.B.all() + ), + ) diff --git a/axelrod/tests/unit/test_history.py b/axelrod/tests/unit/test_history.py index 11cd2445c..7c3fa6ef7 100644 --- a/axelrod/tests/unit/test_history.py +++ b/axelrod/tests/unit/test_history.py @@ -92,6 +92,13 @@ def test_flip_plays(self): self.assertEqual(flipped_flipped_history.defections, 2) +def test_coplays(): + plays = (C, C, D) + coplays = (C, C, C) + history = History(plays=plays, coplays=coplays) + assert history.coplays == list(coplays) + + class TestLimitedHistory(unittest.TestCase): def test_memory_depth(self): h = LimitedHistory(memory_depth=3) diff --git a/axelrod/tests/unit/test_match.py b/axelrod/tests/unit/test_match.py index 6012ce32f..9f52c66fd 100644 --- a/axelrod/tests/unit/test_match.py +++ b/axelrod/tests/unit/test_match.py @@ -1,12 +1,13 @@ import unittest from collections import Counter +from hypothesis import example, given +from hypothesis.strategies import floats, integers + import axelrod as axl from axelrod.deterministic_cache import DeterministicCache from axelrod.random_ import RandomGenerator from axelrod.tests.property import games -from hypothesis import example, given -from hypothesis.strategies import floats, integers C, D = axl.Action.C, axl.Action.D diff --git a/axelrod/tests/unit/test_match_generator.py b/axelrod/tests/unit/test_match_generator.py index 730928216..437b47c96 100644 --- a/axelrod/tests/unit/test_match_generator.py +++ b/axelrod/tests/unit/test_match_generator.py @@ -1,10 +1,11 @@ import unittest -import axelrod as axl -from axelrod.match_generator import graph_is_connected from hypothesis import example, given, settings from hypothesis.strategies import integers +import axelrod as axl +from axelrod.match_generator import graph_is_connected + test_strategies = [ axl.Cooperator, axl.TitForTat, diff --git a/axelrod/tests/unit/test_moran.py b/axelrod/tests/unit/test_moran.py index 84014d448..2566118af 100644 --- a/axelrod/tests/unit/test_moran.py +++ b/axelrod/tests/unit/test_moran.py @@ -2,13 +2,14 @@ import unittest from collections import Counter -import axelrod as axl import matplotlib.pyplot as plt -from axelrod import MoranProcess -from axelrod.tests.property import strategy_lists from hypothesis import example, given, settings from hypothesis.strategies import integers +import axelrod as axl +from axelrod import MoranProcess +from axelrod.tests.property import strategy_lists + C, D = axl.Action.C, axl.Action.D random = axl.RandomGenerator() @@ -194,7 +195,9 @@ def test_different_game(self): def test_different_match(self): """Test alternative Match class, mainly to show that the results are different - than the results of `test_different_game` where the same seed is used.""" + than the results of `test_different_game` where the same seed is used. + """ + # Using a different game where the scores are all constant class StandInMatch(axl.Match): """A Match were all players get a score of 3""" diff --git a/axelrod/tests/unit/test_plot.py b/axelrod/tests/unit/test_plot.py index f84546135..0db464361 100644 --- a/axelrod/tests/unit/test_plot.py +++ b/axelrod/tests/unit/test_plot.py @@ -2,12 +2,13 @@ import tempfile import unittest -import axelrod as axl import matplotlib import matplotlib.pyplot as plt -from axelrod.load_data_ import axl_filename from numpy import mean +import axelrod as axl +from axelrod.load_data_ import axl_filename + class TestPlot(unittest.TestCase): @classmethod diff --git a/axelrod/tests/unit/test_property.py b/axelrod/tests/unit/test_property.py index 945aae5be..9e3265878 100644 --- a/axelrod/tests/unit/test_property.py +++ b/axelrod/tests/unit/test_property.py @@ -1,5 +1,7 @@ import unittest +from hypothesis import given, settings + import axelrod as axl from axelrod.tests.property import ( games, @@ -10,7 +12,6 @@ strategy_lists, tournaments, ) -from hypothesis import given, settings stochastic_strategies = [ s for s in axl.strategies if axl.Classifiers["stochastic"](s()) diff --git a/axelrod/tests/unit/test_random_.py b/axelrod/tests/unit/test_random_.py index e64ee5536..1b27b40e6 100644 --- a/axelrod/tests/unit/test_random_.py +++ b/axelrod/tests/unit/test_random_.py @@ -1,4 +1,5 @@ """Tests for the random functions.""" + import unittest from collections import Counter diff --git a/axelrod/tests/unit/test_resultset.py b/axelrod/tests/unit/test_resultset.py index bb0aa2091..33b1e7f78 100644 --- a/axelrod/tests/unit/test_resultset.py +++ b/axelrod/tests/unit/test_resultset.py @@ -3,15 +3,16 @@ import unittest from collections import Counter -import axelrod as axl import pandas as pd -from axelrod.load_data_ import axl_filename -from axelrod.result_set import create_counter_dict -from axelrod.tests.property import prob_end_tournaments, tournaments from dask.dataframe.core import DataFrame from hypothesis import given, settings from numpy import mean, nanmedian, std +import axelrod as axl +from axelrod.load_data_ import axl_filename +from axelrod.result_set import create_counter_dict +from axelrod.tests.property import prob_end_tournaments, tournaments + C, D = axl.Action.C, axl.Action.D @@ -746,6 +747,7 @@ def setUpClass(cls): cls.filename = str(axl_filename(path)) cls.players = [axl.Alternator(), axl.TitForTat(), axl.Defector()] cls.turns = 5 + cls.repetitions = 3 cls.edges = [(0, 1), (0, 2)] cls.expected_match_lengths = [ @@ -956,6 +958,7 @@ def setUpClass(cls): axl.Cooperator(), ] cls.turns = 5 + cls.repetitions = 3 cls.edges = [(0, 1), (2, 3)] cls.expected_match_lengths = [ @@ -1179,6 +1182,7 @@ def setUpClass(cls): axl.Cooperator(), ] cls.turns = 5 + cls.repetitions = 3 cls.edges = [(0, 0), (1, 1), (2, 2), (3, 3)] cls.expected_match_lengths = [ diff --git a/axelrod/tests/unit/test_strategy_utils.py b/axelrod/tests/unit/test_strategy_utils.py index fb286a052..797dfe8bd 100644 --- a/axelrod/tests/unit/test_strategy_utils.py +++ b/axelrod/tests/unit/test_strategy_utils.py @@ -1,14 +1,16 @@ """Tests for the strategy utils.""" + import unittest +from hypothesis import given, settings +from hypothesis.strategies import integers, lists, sampled_from + import axelrod as axl from axelrod._strategy_utils import ( detect_cycle, recursive_thue_morse, thue_morse_generator, ) -from hypothesis import given, settings -from hypothesis.strategies import integers, lists, sampled_from C, D = axl.Action.C, axl.Action.D diff --git a/axelrod/tests/unit/test_tournament.py b/axelrod/tests/unit/test_tournament.py index 87f4f2269..d7e8fcd1b 100644 --- a/axelrod/tests/unit/test_tournament.py +++ b/axelrod/tests/unit/test_tournament.py @@ -1,4 +1,5 @@ """Tests for the main tournament class.""" + import io import logging import os @@ -9,9 +10,13 @@ from multiprocessing import Queue, cpu_count from unittest.mock import MagicMock, patch -import axelrod as axl import numpy as np import pandas as pd +from hypothesis import example, given, settings +from hypothesis.strategies import floats, integers +from tqdm import tqdm + +import axelrod as axl from axelrod.load_data_ import axl_filename from axelrod.tests.property import ( prob_end_tournaments, @@ -20,9 +25,6 @@ tournaments, ) from axelrod.tournament import _close_objects -from hypothesis import example, given, settings -from hypothesis.strategies import floats, integers -from tqdm import tqdm C, D = axl.Action.C, axl.Action.D diff --git a/axelrod/tournament.py b/axelrod/tournament.py index 42088a4d4..c79775489 100644 --- a/axelrod/tournament.py +++ b/axelrod/tournament.py @@ -7,8 +7,9 @@ from tempfile import mkstemp from typing import List, Optional, Tuple -import axelrod.interaction_utils as iu import tqdm + +import axelrod.interaction_utils as iu from axelrod import DEFAULT_TURNS from axelrod.action import Action, actions_to_str from axelrod.player import Player diff --git a/axelrod/version.py b/axelrod/version.py index 5b886240e..9c8b8e07d 100644 --- a/axelrod/version.py +++ b/axelrod/version.py @@ -1 +1 @@ -__version__ = "4.13.0" +__version__ = "4.14.0" diff --git a/docs/how-to/contributing/guidelines.rst b/docs/how-to/contributing/guidelines.rst index 3232ad9ac..c99a30b78 100644 --- a/docs/how-to/contributing/guidelines.rst +++ b/docs/how-to/contributing/guidelines.rst @@ -5,27 +5,24 @@ All contributions to this repository are welcome via pull request on the `github The project follows the following guidelines: -1. Use the base Python library unless completely necessary. A few external - libraries (such as numpy) have been included in requirements.txt -- feel free - to use these as needed. -2. Try as best as possible to follow `PEP8 +1. Try as best as possible to follow `PEP8 `_ which includes **using descriptive variable names**. -3. Code Format: Use the `Black formatter `_ to format +2. Code Format: Use the `Black formatter `_ to format all code and the `isort utility `_ to sort import statements. You can run black on all code with:: $ python -m black -l 80 . -4. Commits: Please try to use commit messages that give a meaningful history +3. Commits: Please try to use commit messages that give a meaningful history for anyone using git's log features. Try to use messages that complete sentence, "This commit will..." There is some excellent guidance on the subject from `Chris Beams `_ -5. Testing: the project uses the `unittest +4. Testing: the project uses the `unittest `_ library and has a nice testing suite that makes some things easy to write tests for. Please try to increase the test coverage on pull requests. -6. Merging pull-requests: We require two of the (currently three) core-team +5. Merging pull-requests: We require two of the (currently three) core-team maintainers to merge. Opening a PR for early feedback or to check test coverage is OK, just indicate that the PR is not ready to merge (and update when it is). diff --git a/docs/how-to/contributing/running_tests.rst b/docs/how-to/contributing/running_tests.rst index f3ca6d961..58babc0ee 100644 --- a/docs/how-to/contributing/running_tests.rst +++ b/docs/how-to/contributing/running_tests.rst @@ -8,20 +8,23 @@ The project has an extensive test suite which is run each time a new contribution is made to the repository. If you want to check that all the tests pass before you submit a pull request you can run the tests yourself:: - $ python -m unittest discover + $ python -m tox + +This will run the entire test suite in an isolated environment for all currently +supported versions of Python. If you are developing new tests for the suite, it is useful to run a single test file so that you don't have to wait for the entire suite each time. For example, to run only the tests for the Grudger strategy:: - $ python -m unittest axelrod.tests.strategies.test_grudger + $ python -m pytest axelrod/tests/strategies/test_grudger.py The test suite is divided into three categories: strategy tests, unit tests and integration tests. Each can be run individually:: - $ python -m unittest discover -s axelrod.tests.strategies - $ python -m unittest discover -s axelrod.tests.unit - $ python -m unittest discover -s axelrod.tests.integration + $ python -m pytest axelrod/tests/strategies/ + $ python -m pytest axelrod/tests/unit/ + $ python -m pytest axelrod/tests/integration/ Testing coverage of tests @@ -31,7 +34,7 @@ The library has 100% test coverage. This can be tested using the Python :code:`coverage` package. Once installed (:code:`pip install coverage`), to run the tests and check the coverage for the entire library:: - $ coverage run --source=axelrod -m unittest discover + $ coverage run --source=axelrod -m pytest . You can then view a report of the coverage:: @@ -40,7 +43,7 @@ You can then view a report of the coverage:: You can also run the coverage on a subset of the tests. For example, to run the tests with coverage for the Grudger strategy:: - $ coverage run --source=axelrod -m unittest axelrod.tests.strategies.test_grudger + $ coverage run --source=axelrod -m pytest axelrod/tests/strategies/test_grudger.py Testing the documentation @@ -55,17 +58,3 @@ You can also run the doctests on any given file. For example, to run the doctests for the :code:`docs/tutorials/getting_started/match.rst` file:: $ python -m doctest docs/tutorials/getting_started/match.rst - - -Type checking -------------- - -The library makes use of type hinting, this can be checked using the Python -:code:`mypy` package. Once installed (:code:`pip install mypy`), to run the type checker:: - - $ python run_mypy.py - -You can also run the type checker on a given file. For example, to run the type -checker on the Grudger strategy:: - - $ mypy --ignore-missing-imports --follow-imports skip axelrod/strategies/grudger.py diff --git a/docs/tutorials/new_to_game_theory_and_or_python/human_interaction.rst b/docs/tutorials/new_to_game_theory_and_or_python/human_interaction.rst deleted file mode 100644 index d69a63473..000000000 --- a/docs/tutorials/new_to_game_theory_and_or_python/human_interaction.rst +++ /dev/null @@ -1,29 +0,0 @@ -.. _human-interaction: - -Human Interaction -================= - -It is possible to play interactively using the Human strategy:: - - >>> import axelrod as axl - >>> me = axl.Human(name='me') - >>> players = [axl.TitForTat(), me] - >>> match = axl.Match(players, turns=3) - >>> match.play() #doctest: +SKIP - -You will be prompted for the action to play at each turn: - -.. code-block:: bash - - Starting new match - Turn 1 action [C or D] for me: C - - Turn 1: me played C, opponent played C - Turn 2 action [C or D] for me: D - - Turn 2: me played D, opponent played C - Turn 3 action [C or D] for me: C - [(C, C), (C, D), (D, C)] - -after this, the :code:`match` object can be manipulated as described in -:ref:`creating_matches` diff --git a/docs/tutorials/new_to_game_theory_and_or_python/index.rst b/docs/tutorials/new_to_game_theory_and_or_python/index.rst index 8186ed97a..74ad3cab9 100644 --- a/docs/tutorials/new_to_game_theory_and_or_python/index.rst +++ b/docs/tutorials/new_to_game_theory_and_or_python/index.rst @@ -15,4 +15,3 @@ Contents: summarising_tournaments.rst visualising_results.rst moran.rst - human_interaction.rst diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000..cc79198da --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,54 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "Axelrod" +dynamic = ["version"] +description = "Reproduce the Axelrod iterated prisoners dilemma tournament" +readme = "README.rst" +license = {file = "LICENSE.txt"} +requires-python = ">=3.6" +authors = [ + { name = "Vince Knight", email = "axelrod-python@googlegroups.com" }, + { name = "Owen Campbell" }, + { name = "Karol Langner" }, + { name = "Marc Harper" }, +] +classifiers = [ + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: MIT License", +] +dependencies = [ + "cloudpickle>=0.2.2", + "dask[dataframe]>=2.9.2", + "fsspec>=0.6.0", + "matplotlib>=3.0.3", + "numpy>=1.17.4", + "pandas>=1.0.0", + "pyyaml>=5.1", + "scipy>=1.3.3", + "toolz>=0.8.2", + "tqdm>=4.39.0", +] + +[project.optional-dependencies] +development = [ + "hypothesis==5.19.3", +] +human = [ + "prompt-toolkit>=3.0", +] + +[project.urls] +Homepage = "http://axelrod.readthedocs.org/" + +[tool.hatch.version] +path = "axelrod/version.py" + +[tool.hatch.build.targets.sdist] +include = [ + "axelrod", +] diff --git a/requirements/development.txt b/requirements/development.txt deleted file mode 100644 index ebe5ad6aa..000000000 --- a/requirements/development.txt +++ /dev/null @@ -1,3 +0,0 @@ --r requirements.txt --r human.txt -hypothesis==5.19.3 diff --git a/requirements/human.txt b/requirements/human.txt deleted file mode 100644 index d595d21e2..000000000 --- a/requirements/human.txt +++ /dev/null @@ -1,2 +0,0 @@ --r requirements.txt -prompt-toolkit>=3.0 diff --git a/requirements/requirements.txt b/requirements/requirements.txt deleted file mode 100644 index f0c611e2d..000000000 --- a/requirements/requirements.txt +++ /dev/null @@ -1,12 +0,0 @@ -# dask dependencies: https://docs.dask.org/en/latest/install.html -cloudpickle>=0.2.2 -fsspec>=0.6.0 -toolz>=0.8.2 -dask>=2.9.2 - -matplotlib>=3.0.3 -numpy>=1.17.4 -pandas>=1.0.0 -pyyaml>=5.1 -scipy>=1.3.3 -tqdm>=4.39.0 diff --git a/run_strategy_indexer.py b/run_strategy_indexer.py index 275641c99..49d100a6c 100644 --- a/run_strategy_indexer.py +++ b/run_strategy_indexer.py @@ -2,11 +2,12 @@ A script to check that all strategy modules have been included in `./docs/reference/all_strategies.rst` """ + import pathlib import sys default_index_path = pathlib.Path("./docs/reference/strategy_index.rst") -excluded_modules = ("_strategies", "__init__", "_filters", "human") +excluded_modules = ("_strategies", "__init__", "_filters") def check_module( diff --git a/tox.ini b/tox.ini new file mode 100644 index 000000000..09df4e943 --- /dev/null +++ b/tox.ini @@ -0,0 +1,34 @@ +[tox] +isolated_build = True +envlist = py311, py312 + +[gh-actions] +python = + 3.11: py311 + 3.12: py312 + +[flake8] +per-file-ignores = + setup.py: F821 + docs/_build/*: ALL + docs/conf.py: E402 + **/__init__.py: F401 F403 +ignore = + E203 + E501 + W291 + W503 + +[testenv] +deps = + hypothesis + pytest-cov + pytest-randomly + pytest-sugar + isort + black +commands = + python -m pytest --cov-report term-missing --cov=axelrod --cov-fail-under=100 . --doctest-glob="*.md" --doctest-glob="*.rst" + python -m black -l 80 . --check + python -m isort --check-only axelrod/. + python run_strategy_indexer.py