def test_fetch_cached_price__historical(self): tmpdir = tempfile.mkdtemp() tmpfile = path.join(tmpdir, 'prices.cache') try: price.setup_cache(tmpfile, False) srcprice = SourcePrice(D('1.723'), datetime.datetime.now(tz.tzutc()), 'USD') source = mock.MagicMock() source.get_historical_price.return_value = srcprice source.__file__ = '<module>' # Cache miss. day = datetime.date(2006, 1, 2) result = price.fetch_cached_price(source, 'HOOL', day) self.assertTrue(source.get_historical_price.called) self.assertEqual(1, len(price._CACHE)) self.assertEqual(srcprice, result) source.get_historical_price.reset_mock() # Cache hit. result = price.fetch_cached_price(source, 'HOOL', day) self.assertFalse(source.get_historical_price.called) self.assertEqual(1, len(price._CACHE)) self.assertEqual(srcprice, result) finally: price.reset_cache() if path.exists(tmpdir): shutil.rmtree(tmpdir)
def test_fetch_cached_price__disabled(self): # Latest. with mock.patch('beancount.prices.price._CACHE', None): self.assertIsNone(price._CACHE) source = mock.MagicMock() price.fetch_cached_price(source, 'HOOL', None) self.assertTrue(source.get_latest_price.called) # Historical. with mock.patch('beancount.prices.price._CACHE', None): self.assertIsNone(price._CACHE) source = mock.MagicMock() price.fetch_cached_price(source, 'HOOL', datetime.date.today()) self.assertTrue(source.get_historical_price.called)
def test_fetch_cached_price__latest(self): tmpdir = tempfile.mkdtemp() tmpfile = path.join(tmpdir, 'prices.cache') try: price.setup_cache(tmpfile, False) srcprice = SourcePrice(D('1.723'), datetime.datetime.now(tz.tzutc()), 'USD') source = mock.MagicMock() source.get_latest_price.return_value = srcprice source.__file__ = '<module>' # Cache miss. result = price.fetch_cached_price(source, 'HOOL', None) self.assertTrue(source.get_latest_price.called) self.assertEqual(1, len(price._CACHE)) self.assertEqual(srcprice, result) source.get_latest_price.reset_mock() # Cache hit. result = price.fetch_cached_price(source, 'HOOL', None) self.assertFalse(source.get_latest_price.called) self.assertEqual(1, len(price._CACHE)) self.assertEqual(srcprice, result) srcprice2 = SourcePrice(D('1.894'), datetime.datetime.now(tz.tzutc()), 'USD') source.get_latest_price.reset_mock() source.get_latest_price.return_value = srcprice2 # Cache expired. time_beyond = datetime.datetime.now() + price._CACHE.expiration * 2 with mock.patch('beancount.prices.price.now', return_value=time_beyond): result = price.fetch_cached_price(source, 'HOOL', None) self.assertTrue(source.get_latest_price.called) self.assertEqual(1, len(price._CACHE)) self.assertEqual(srcprice2, result) finally: price.reset_cache() if path.exists(tmpdir): shutil.rmtree(tmpdir)