Skip to content

Commit

Permalink
Change EvolvablePlayer serialization to write strings instead of bytes (
Browse files Browse the repository at this point in the history
#1267)

* Change EvolvablePlayer serialization to write strings instead of bytes for easier inclusion in CSV files

* Add serialization test
  • Loading branch information
marcharper authored and drvinceknight committed Oct 21, 2019
1 parent 72a5148 commit bda5ba5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
7 changes: 5 additions & 2 deletions axelrod/evolvable_player.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import base64
from pickle import dumps, loads
from random import randrange
from typing import Dict, List
Expand Down Expand Up @@ -36,12 +37,14 @@ def create_new(self, **kwargs):

def serialize_parameters(self):
"""Serialize parameters."""
return dumps(self.init_kwargs)
pickled = dumps(self.init_kwargs) # bytes
s = base64.b64encode(pickled).decode('utf8') # string
return s

@classmethod
def deserialize_parameters(cls, serialized):
"""Deserialize parameters to a Player instance."""
init_kwargs = loads(serialized)
init_kwargs = loads(base64.b64decode(serialized))
return cls(**init_kwargs)

# Optional methods for evolutionary algorithms and Moran processes.
Expand Down
11 changes: 11 additions & 0 deletions axelrod/tests/strategies/test_evolvable_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,17 @@ def test_serialization(self):
self.assertEqual(player, deserialized_player)
self.assertEqual(deserialized_player, deserialized_player.clone())

def test_serialization_csv(self):
"""Serializing and deserializing should return the original player."""
seed(0)
player = self.player()
serialized = player.serialize_parameters()
s = "0, 1, {}, 3".format(serialized)
s2 = s.split(',')[2]
deserialized_player = player.__class__.deserialize_parameters(s2)
self.assertEqual(player, deserialized_player)
self.assertEqual(deserialized_player, deserialized_player.clone())

def behavior_test(self, player1, player2):
"""Test that the evolvable player plays the same as its (nonevolvable) parent class."""
for opponent_class in [axl.Random, axl.TitForTat, axl.Alternator]:
Expand Down

0 comments on commit bda5ba5

Please sign in to comment.