changeset 21:bdc6bfc34ef2

Serialise lab data.
author Jeremy Thurgood <firxen@gmail.com>
date Sun, 06 May 2012 18:34:28 +0200
parents 718d1ec382f7
children 296ce36fa7d9
files gamelib/lab.py gamelib/tests/test_lab.py
diffstat 2 files changed, 30 insertions(+), 11 deletions(-) [+]
line wrap: on
line diff
--- a/gamelib/lab.py	Sun May 06 18:12:51 2012 +0200
+++ b/gamelib/lab.py	Sun May 06 18:34:28 2012 +0200
@@ -32,6 +32,15 @@
                 raise ValueError("Unknown science type: %s" % (module,))
             self._gain_science(science(points))
 
+    def save_data(self):
+        data = {'science': {}}
+        for science in self.science:
+            science_class = type(science)
+            name = "%s.%s" % (science_class.__module__.split('.')[-1],
+                              science_class.__name__)
+            data['science'][name] = science.points
+        return data
+
     def _choose_initial_science(self):
         # We always get all starting products.
         for product in self.new_products[:]:
--- a/gamelib/tests/test_lab.py	Sun May 06 18:12:51 2012 +0200
+++ b/gamelib/tests/test_lab.py	Sun May 06 18:34:28 2012 +0200
@@ -4,6 +4,15 @@
 from gamelib import research, products
 
 
+LAB_DATA = {
+    'science': {
+        'research.Robotics': 1,
+        'research.Rocketry': 2,
+        'research.Tesla': 3,
+        },
+    }
+
+
 class TestLab(TestCase):
     def test_new_lab(self):
         all_sciences = set()
@@ -17,22 +26,23 @@
         self.assertTrue(len(all_sciences) > 3)
 
     def test_find_new_products(self):
-        lab = Lab({
-                'science': {
-                    'research.Tesla': 3,
-                    }
-                })
+        lab = Lab(LAB_DATA)
         new_products = lab.find_new_products(None)
         self.assertTrue(products.TeslaTank in new_products)
         self.assertTrue(products.DoomsdayVirus not in new_products)
 
     def test_find_new_research(self):
-        lab = Lab({
-                'science': {
-                    'research.Robotics': 1,
-                    'research.Rocketry': 2,
-                    }
-                })
+        lab = Lab(LAB_DATA)
         new_research = lab.find_new_research()
         self.assertTrue(research.Space in new_research)
         self.assertTrue(research.ArtificialIntelligence not in new_research)
+
+    def test_save_data(self):
+        # Check that we save what we loaded.
+        lab = Lab(LAB_DATA)
+        self.assertEqual(LAB_DATA, lab.save_data())
+        # Add a product and check that it gets saved as well.
+        lab._gain_science(products.LightningGun())
+        new_science = dict(
+            LAB_DATA['science'].items() + [('products.LightningGun', 0)])
+        self.assertEqual({'science': new_science}, lab.save_data())