def test_log_name(self): log_dir = '/var/log' KM.init('key', to_stderr=False, log_dir=log_dir) self.assertEqual(KM.log_name('invalid'), os.path.join(log_dir, '')) self.assertEqual(KM.log_name('error'), os.path.join(log_dir, 'kissmetrics_error.log')) self.assertEqual(KM.log_name('query'), os.path.join(log_dir, 'kissmetrics_query.log')) send_name = KM.log_name('send') self.assertStartsWith(send_name, log_dir) self.assertEndsWith(send_name, 'kissmetrics_sending.log') self.assertEqual(KM.log_name('send'), send_name)
def test_send_logged_queries(self): host = 'example.com' line = '/type?foo=1&bar=2' with LogDir() as log_dir: KM.init('key', host=host, log_dir=log_dir) # Write line to the query log KM.log_query(line) # Expect that line to be requested urlopen = self.mocker.replace('urllib2.urlopen') urlopen('http://%s%s' % (host, line)) self.mocker.result(None) with self.mocker: KM.send_logged_queries() self.assertFalse(os.path.exists(KM.log_name('query'))) self.assertFalse(os.path.exists(KM.log_name('send')))
def get_log(self, log_name): try: with open(KM.log_name(log_name), 'r') as log_file: yield log_file except IOError, e: if e.errno == errno.ENOENT: yield None
def assertQuery(self, type, data, update=True): host = 'example.com' _t = 1 _k = 'key' _p = 'id' with LogDir() as log_dir: KM.init(_k, host=host, to_stderr=False, log_dir=log_dir, use_cron=True) KM.identify(_p) # Ensure time.time() always returns the same value time = self.mocker.replace('time.time') time() self.mocker.result(_t) self.mocker.count(0, None) with self.mocker: yield with self.get_log('query') as log: data = dict(data, _t=str(_t), _k=_k) if update: data['_p'] = _p line = log.readline().strip() bits = urlparse.urlsplit(line) self.assertEqual(bits[2], '/%s' % urllib.quote(type)) self.assertEqual(dict(parse_qsl(bits[3])), data) self.assertEqual(log.readline(), '') os.unlink(KM.log_name('query'))