def test_get_record(self): expected = self.focus_record actual = NistBeacon.get_record(self.target_timestamp) self.assertTrue(actual.valid_signature) self.assertEqual(expected, actual) self.assertIsNot(expected, actual)
def test_get_record(self, requests_get_patched): mock_response = Mock(spec=Response) mock_response.status_code = 200 mock_response.text = self.expected_current.xml requests_get_patched.return_value = mock_response record = NistBeacon.get_record(self.reference_timestamp) self.assertEqual(self.expected_current, record)
def test_get_record_404(self): expected = self.future_record actual = NistBeacon.get_record(self.future_timestamp) self.assertIsNone(actual) self.assertEqual(expected, actual)
class NistBeaconRandom(random.Random): '''Random number generator base class''' def __init__(self, seed=None): """Initialize an instance. """ if seed == None: self.timestamp = 1378395540 # this is the first possible timestamp else: self.timestamp = seed self.beacon = NistBeacon() def get_value(self): """ Get a random number from the server """ val = self.beacon.get_record(self.timestamp).output_value return int(val,16) def next(self): """ Update the counter """ self.timestamp += 60 # 60 seconds = 1 step def getstate(self): return (self.timestamp) def jumpahead(self, n): """ Jump ahead n steps in time """ self.timestamp += n*60 self.get_value() def __repr__(self): """ >>> r = true_random() >>> repr(r) 'True RNG with Timestamp 0' >>> str(r) 'True RNG with Timestamp 0' """ stringrepr = "True RNG with Timestamp " + str(self.timestamp) return stringrepr def random(self, size=None): """ Generate random numbers between 0 and 1. size controls the number of ints generated. If size=None, just one is produced. """ if size==None: return self.nextRandom()*RECIP_BITLEN else: return np.reshape(np.array([self.nextRandom()*RECIP_BITLEN for i in np.arange(np.prod(size))]), size) def nextRandom(self): """ Generate the next random number """ val = self.get_value() self.next() return(val) def randint(self, a, b, size=None): """ Generate random integers between a (inclusive) and b (exclusive). size controls the number of ints generated. If size=None, just one is produced. """ assert a <= b, "lower and upper limits are switched" if size==None: return a + (self.nextRandom() % (b-a)) else: return np.reshape(np.array([a + (self.nextRandom() % (b-a)) for i in np.arange(np.prod(size))]), size)