-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_helpers.py
66 lines (56 loc) · 1.88 KB
/
test_helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import random
import pytest
from helpers import check_winners
from helpers import crossover
from helpers import populate
from helpers import select
from player import Player
def test_populate():
players = populate(size=10, mutation_rate=0.1)
assert len(players) == 10
for player in players:
assert isinstance(player, Player)
assert len(player.dna) == 11
def test_select():
players = [
Player(id=i, dna=(["↑"] * (11 - i) + ["↓"] * i), mutation_rate=0.0)
for i in range(11)
]
# Add a player with perfect score for testing efficacy of select.
players.append(
Player(
id=11,
dna=["↑", "↑", "↓", "↓", "←", "→", "←", "→", "B", "A", "START"],
mutation_rate=0.0,
)
)
survivors = select(players, fitness_cutoff=5)
assert len(survivors) == 5
assert survivors[0].score == 11
def test_crossover():
random.seed(42)
parents = [
Player(id=0, dna=["↑"] * 11, mutation_rate=0.0),
Player(id=1, dna=["↓"] * 11, mutation_rate=0.0),
]
offspring = crossover(survivors=parents, size=10, mutation_rate=0.0)
assert len(offspring) == 10
# With 0% mutation rate, all offpsring should only have "↑" or "↓" genes.
for child in offspring:
assert all(gene in ["↑", "↓"] for gene in child.dna)
@pytest.mark.parametrize(
"win_gene, win",
[pytest.param("↑", True, id="Win"), pytest.param("↓", False, id="Lose")],
)
def test_check_winners(win_gene: str, win: bool):
# Modify only the first gene to determine win case or lose case.
dna = [win_gene, "↑", "↓", "↓", "←", "→", "←", "→", "B", "A", "START"]
players = [
Player(
id=i,
dna=dna,
mutation_rate=0.0,
)
for i in range(10)
]
assert check_winners(players, win_percent=1.0) is win