Commits

Robert Brewer committed abe0e39

Expanded the basic workflow test

  • Participants
  • Parent commits 4681778

Comments (0)

Files changed (5)

File flowrate/__init__.py

                 'credit': cherrypy.url("/accounts/%s" % row['credit_account']),
                 'debit': cherrypy.url("/accounts/%s" % row['debit_account']),
                 'postdate': row['postdate'].isoformat(),
+                'description': row['description'],
                 },
             }
 
             raise cherrypy.HTTPError("400 No Body",
                 "Transactions MUST include a 'body' member.")
 
-        credit, debit = popint(vals['credit']), popint(vals['debit'])
-
         # Accept the new transaction definition.
         vals = req.json["body"]
+        credit, debit = popint(vals['credit']), popint(vals['debit'])
         newrow = db.execute(
             "INSERT INTO transactions"
             " (amount, credit_account, debit_account, postdate, description) "
-            "VALUES (%s, %s, %s, %s, %s) RETURNING id",
+            "VALUES (%s, %s, %s, %s, %s) RETURNING *",
             (vals["amount"], credit, debit,
              vals["postdate"], vals['description'])).fetchone()
 

File flowrate/flowrate.sql

     credit_account integer NOT NULL,
     debit_account integer NOT NULL,
     description text,
-    amount numeric(10, 2) NOT NULL,
-    obligationid integer
+    amount numeric(10, 2) NOT NULL
 );
 
 
     ADD CONSTRAINT transactions_debit_account_fkey FOREIGN KEY (debit_account) REFERENCES accounts(id);
 
 
---
--- Name: transactions_obligationid_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
---
-
-ALTER TABLE ONLY transactions
-    ADD CONSTRAINT transactions_obligationid_fkey FOREIGN KEY (obligationid) REFERENCES obligations(id);
-
-
 CREATE OR REPLACE FUNCTION isSubAccount(child integer, parent integer) RETURNS boolean AS $$
   -- Return true if the given child is a subaccount of the given parent.
   SELECT $1 >= $2 AND $1 < $2 + (CASE WHEN $2 % 1000 = 0 THEN 1000

File flowrate/testing/__init__.py

+import difflib
 import os
 thisdir = os.path.abspath(os.path.dirname(__file__))
 import traceback
     def assertEqual(self, x, y, msg=None):
         self.assert_(x == y, msg or "%r != %r" % (x, y))
 
+    def assertJSONEqual(self, expected, actual, msg=None):
+        # Assert supplied members only.
+        def compare(expected, actual):
+            if isinstance(expected, list):
+                if not isinstance(actual, list):
+                    raise AssertionError
+                for a, b in zip(expected, actual):
+                    compare(a, b)
+            elif isinstance(expected, dict):
+                if not isinstance(actual, dict):
+                    raise AssertionError
+                for k, v in expected.iteritems():
+                    m = actual.get(k, None)
+                    compare(v, m)
+            elif expected != actual:
+                raise AssertionError
+
+        try:
+            compare(expected, actual)
+        except AssertionError:
+            A = simplejson.dumps(
+                    expected, sort_keys=True, indent='    ').splitlines()
+            B = simplejson.dumps(
+                    actual, sort_keys=True, indent='    ').splitlines()
+            msg = "\n".join(difflib.unified_diff(
+                A, B, fromfile="expected", tofile="actual"))
+            raise AssertionError("JSON documents do not match.\n" + msg)
+
     def base(self):
         if ((self.scheme == "http" and self.PORT == 80) or
             (self.scheme == "https" and self.PORT == 443)):
         self.getPage(loc)
         self.assertStatus(200)
         self.assertEqual(self.json['body'], kwargs)
+        return loc
 
     def define_flow(self, **kwargs):
         """Add the given flow to the system."""
         self.getPage('/flows/', method="POST", headers=h, body=b)
         self.assertStatus(201)
         loc = self.assertHeader('Location')
-        print loc
         self.getPage(loc)
         self.assertStatus(200)
         self.assertEqual(self.json['body'], kwargs)
+        return loc
 
+    def add_transaction(self, **kwargs):
+        """Add the given transaction to the system."""
+        b = simplejson.dumps({'body': kwargs})
+        h = [('Content-Type', 'application/json'),
+             ('Content-Length', str(len(b)))]
+        self.getPage('/transactions/', method="POST", headers=h, body=b)
+        self.assertStatus(201)
+        loc = self.assertHeader('Location')
+        self.getPage(loc)
+        self.assertStatus(200)
+        self.assertEqual(self.json['body'], kwargs)
+        return loc
+
+    def tx_from_flow(self, flow, **kwargs):
+        tx = {'credit': flow['credit'], 'debit': flow['debit'],
+              'description': flow['description'], 'amount': flow['amount']}
+        tx.update(kwargs)
+        return tx
+
+

File flowrate/testing/db.py

Empty file removed.

File flowrate/testing/test_flowrate.py

 
     def test_basic_workflow(self):
         self.define_account(id=1012, type="asset", name="Checking")
+
+        # Add a flow
         self.define_account(id=3011, type="income", name="Paycheck")
-        self.define_flow(start='2012-01-01', end='2012-12-31',
-                         credit=self.base() + '/accounts/3011',
-                         debit=self.base() + '/accounts/1012',
-                         period=1, unit='months', days=[15, 28],
-                         description='External Deposit MyCompany',
-                         amount=1500)
+        flow = dict(start='2012-01-01', end='2012-12-31',
+                    credit=self.base() + '/accounts/3011',
+                    debit=self.base() + '/accounts/1012',
+                    period=1, unit='months', days=[15, 28],
+                    description='External Deposit MyCompany',
+                    amount=1500.30)
+        self.define_flow(**flow)
 
+        # Assert unfulfilled obligations for the new flow
+        expected = [self.tx_from_flow(flow, postdate='2012-%02d-%02d' % (m, d))
+                    for m in range(1, 13) for d in (15, 28)]
+        self.getPage('/transactions/?accounts=3011&years=2012')
+        self.assertStatus(200)
+        self.assertJSONEqual(self.json['data'], list(reversed(expected)))
+
+        tx = dict(postdate='2012-01-14',
+                  credit=self.base() + '/accounts/3011',
+                  debit=self.base() + '/accounts/1012',
+                  description='External Deposit MyCompany',
+                  amount=1500.0)
+        txloc = self.add_transaction(**tx)
+
+        flowtx2 = self.tx_from_flow(flow, postdate='2012-01-28')
+        flowtx1 = self.tx_from_flow(flow, amount=0.30, postdate='2012-01-15')
+        tx['id'] = txloc
+
+        self.getPage('/transactions/?accounts=3011&years=2012&months=1')
+        self.assertStatus(200)
+        self.assertJSONEqual(self.json['data'], [flowtx2, flowtx1, tx])
+