WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

Commit 7bdf683

Browse files
committed
Replace unittest.TestCase with custom base class. Remove unnecessary code. Adjust test case's code.
1 parent 105be04 commit 7bdf683

File tree

9 files changed

+46
-254
lines changed

9 files changed

+46
-254
lines changed

integrations/acquisition/covidcast/test_covidcast_meta_caching.py

Lines changed: 15 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,13 @@
22

33
# standard library
44
import json
5-
import unittest
65

76
# third party
8-
import mysql.connector
97
import requests
108

119
# first party
1210
from delphi_utils import Nans
13-
from delphi.epidata.client.delphi_epidata import Epidata
14-
import delphi.operations.secrets as secrets
15-
import delphi.epidata.acquisition.covidcast.database as live
11+
from delphi.epidata.common.covidcast_test_base import CovidcastTestBase
1612
from delphi.epidata.maintenance.covidcast_meta_cache_updater import main
1713

1814
# py3tester coverage target (equivalent to `import *`)
@@ -23,86 +19,35 @@
2319

2420
# use the local instance of the Epidata API
2521
BASE_URL = 'http://delphi_web_epidata/epidata'
22+
AUTH = ("epidata", "key")
2623

2724

28-
class CovidcastMetaCacheTests(unittest.TestCase):
25+
class CovidcastMetaCacheTests(CovidcastTestBase):
2926
"""Tests covidcast metadata caching."""
3027

31-
def setUp(self):
32-
"""Perform per-test setup."""
33-
34-
# connect to the `epidata` database
35-
cnx = mysql.connector.connect(
36-
user='user',
37-
password='pass',
38-
host='delphi_database_epidata',
39-
database='covid')
40-
cur = cnx.cursor()
41-
42-
# clear all tables
43-
cur.execute("truncate table epimetric_load")
44-
cur.execute("truncate table epimetric_full")
45-
cur.execute("truncate table epimetric_latest")
46-
cur.execute("truncate table geo_dim")
47-
cur.execute("truncate table signal_dim")
48-
# reset the `covidcast_meta_cache` table (it should always have one row)
49-
cur.execute('update covidcast_meta_cache set timestamp = 0, epidata = "[]"')
50-
cnx.commit()
51-
cur.close()
52-
53-
# make connection and cursor available to test cases
54-
self.cnx = cnx
55-
self.cur = cnx.cursor()
56-
57-
# use the local instance of the epidata database
58-
secrets.db.host = 'delphi_database_epidata'
59-
secrets.db.epi = ('user', 'pass')
60-
61-
epidata_cnx = mysql.connector.connect(
62-
user='user',
63-
password='pass',
64-
host='delphi_database_epidata',
65-
database='epidata')
66-
epidata_cur = epidata_cnx.cursor()
67-
68-
epidata_cur.execute("DELETE FROM `api_user`")
69-
epidata_cur.execute('INSERT INTO `api_user`(`api_key`, `email`) VALUES("key", "email")')
70-
epidata_cnx.commit()
71-
epidata_cur.close()
72-
epidata_cnx.close()
73-
74-
# use the local instance of the Epidata API
75-
Epidata.BASE_URL = BASE_URL
76-
Epidata.auth = ('epidata', 'key')
77-
78-
def tearDown(self):
79-
"""Perform per-test teardown."""
80-
self.cur.close()
81-
self.cnx.close()
82-
8328
@staticmethod
8429
def _make_request():
8530
params = {'cached': 'true'}
86-
response = requests.get(f"{Epidata.BASE_URL}/covidcast_meta", params=params, auth=Epidata.auth)
31+
response = requests.get(f"{BASE_URL}/covidcast_meta", params=params, auth=AUTH)
8732
response.raise_for_status()
8833
return response.json()
8934

9035
def test_caching(self):
9136
"""Populate, query, cache, query, and verify the cache."""
9237

9338
# insert dummy data
94-
self.cur.execute(f'''
39+
self._db._cursor.execute(f'''
9540
INSERT INTO `signal_dim` (`signal_key_id`, `source`, `signal`)
9641
VALUES
9742
(42, 'src', 'sig');
9843
''')
99-
self.cur.execute(f'''
44+
self._db._cursor.execute(f'''
10045
INSERT INTO `geo_dim` (`geo_key_id`, `geo_type`, `geo_value`)
10146
VALUES
10247
(96, 'state', 'pa'),
10348
(97, 'state', 'wa');
10449
''')
105-
self.cur.execute(f'''
50+
self._db._cursor.execute(f'''
10651
INSERT INTO
10752
`epimetric_latest` (`epimetric_id`, `signal_key_id`, `geo_key_id`, `time_type`,
10853
`time_value`, `value_updated_timestamp`,
@@ -115,13 +60,10 @@ def test_caching(self):
11560
(16, 42, 97, 'day', 20200422,
11661
789, 1, 2, 3, 20200423, 1, {Nans.NOT_MISSING}, {Nans.NOT_MISSING}, {Nans.NOT_MISSING})
11762
''')
118-
self.cnx.commit()
63+
self._db._connection.commit()
11964

12065
# make sure the live utility is serving something sensible
121-
cvc_database = live.Database()
122-
cvc_database.connect()
123-
epidata1 = cvc_database.compute_covidcast_meta()
124-
cvc_database.disconnect(False)
66+
epidata1 = self._db.compute_covidcast_meta()
12567
self.assertEqual(len(epidata1),1)
12668
self.assertEqual(epidata1, [
12769
{
@@ -146,26 +88,26 @@ def test_caching(self):
14688

14789
# make sure the API covidcast_meta is still blank, since it only serves
14890
# the cached version and we haven't cached anything yet
149-
epidata2 = Epidata.covidcast_meta()
91+
epidata2 = self.epidata_client.covidcast_meta()
15092
self.assertEqual(epidata2['result'], -2, json.dumps(epidata2))
15193

15294
# update the cache
15395
args = None
15496
main(args)
15597

15698
# fetch the cached version
157-
epidata3 = Epidata.covidcast_meta()
99+
epidata3 = self.epidata_client.covidcast_meta()
158100

159101
# cached version should now equal live version
160102
self.assertEqual(epidata1, epidata3)
161103

162104
# insert dummy data timestamped as of now
163-
self.cur.execute('''
105+
self._db._cursor.execute('''
164106
update covidcast_meta_cache set
165107
timestamp = UNIX_TIMESTAMP(NOW()),
166108
epidata = '[{"hello": "world"}]'
167109
''')
168-
self.cnx.commit()
110+
self._db._connection.commit()
169111

170112
# fetch the cached version (manually)
171113
epidata4 = self._make_request()
@@ -180,12 +122,12 @@ def test_caching(self):
180122
})
181123

182124
# insert dummy data timestamped as 2 hours old
183-
self.cur.execute('''
125+
self._db._cursor.execute('''
184126
update covidcast_meta_cache set
185127
timestamp = UNIX_TIMESTAMP(NOW()) - 3600 * 2,
186128
epidata = '[{"hello": "world"}]'
187129
''')
188-
self.cnx.commit()
130+
self._db._connection.commit()
189131

190132
# fetch the cached version (manually)
191133
epidata5 = self._make_request()

integrations/acquisition/covidcast/test_csv_uploading.py

Lines changed: 10 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -3,80 +3,23 @@
33
# standard library
44
from datetime import date
55
import os
6-
import unittest
7-
import argparse
86

97
# third party
10-
import mysql.connector
118
import pandas as pd
129
import numpy as np
1310

1411
# first party
1512
from delphi_utils import Nans
16-
from delphi.epidata.client.delphi_epidata import Epidata
1713
from delphi.epidata.acquisition.covidcast.csv_to_database import main, get_argument_parser
18-
import delphi.operations.secrets as secrets
14+
from delphi.epidata.common.covidcast_test_base import CovidcastTestBase
1915

2016
# py3tester coverage target (equivalent to `import *`)
2117
__test_target__ = 'delphi.epidata.acquisition.covidcast.csv_to_database'
2218

2319

24-
class CsvUploadingTests(unittest.TestCase):
20+
class CsvUploadingTests(CovidcastTestBase):
2521
"""Tests covidcast CSV uploading."""
2622

27-
def setUp(self):
28-
"""Perform per-test setup."""
29-
30-
# connect to the `epidata` database and clear the `covidcast` table
31-
cnx = mysql.connector.connect(
32-
user='user',
33-
password='pass',
34-
host='delphi_database_epidata',
35-
database='covid')
36-
cur = cnx.cursor()
37-
38-
# clear all tables
39-
cur.execute("truncate table epimetric_load")
40-
cur.execute("truncate table epimetric_full")
41-
cur.execute("truncate table epimetric_latest")
42-
cur.execute("truncate table geo_dim")
43-
cur.execute("truncate table signal_dim")
44-
# reset the `covidcast_meta_cache` table (it should always have one row)
45-
cur.execute('update covidcast_meta_cache set timestamp = 0, epidata = "[]"')
46-
47-
cnx.commit()
48-
cur.close()
49-
50-
# make connection and cursor available to test cases
51-
self.cnx = cnx
52-
self.cur = cnx.cursor()
53-
54-
# use the local instance of the epidata database
55-
secrets.db.host = 'delphi_database_epidata'
56-
secrets.db.epi = ('user', 'pass')
57-
58-
epidata_cnx = mysql.connector.connect(
59-
user='user',
60-
password='pass',
61-
host='delphi_database_epidata',
62-
database='epidata')
63-
epidata_cur = epidata_cnx.cursor()
64-
65-
epidata_cur.execute("DELETE FROM `api_user`")
66-
epidata_cur.execute('INSERT INTO `api_user`(`api_key`, `email`) VALUES("key", "email")')
67-
epidata_cnx.commit()
68-
epidata_cur.close()
69-
epidata_cnx.close()
70-
71-
# use the local instance of the Epidata API
72-
Epidata.BASE_URL = 'http://delphi_web_epidata/epidata'
73-
Epidata.auth = ('epidata', 'key')
74-
75-
def tearDown(self):
76-
"""Perform per-test teardown."""
77-
self.cur.close()
78-
self.cnx.close()
79-
8023
@staticmethod
8124
def apply_lag(expected_epidata):
8225
expected_issue_day=date.today()
@@ -91,11 +34,11 @@ def apply_lag(expected_epidata):
9134
return expected_epidata
9235

9336
def verify_timestamps_and_defaults(self):
94-
self.cur.execute('''
37+
self._db._cursor.execute('''
9538
select value_updated_timestamp from epimetric_full
9639
UNION ALL
9740
select value_updated_timestamp from epimetric_latest''')
98-
for (value_updated_timestamp,) in self.cur:
41+
for (value_updated_timestamp,) in self._db._cursor:
9942
self.assertGreater(value_updated_timestamp, 0)
10043

10144
def test_uploading(self):
@@ -130,7 +73,7 @@ def test_uploading(self):
13073

13174
# upload CSVs
13275
main(args)
133-
response = Epidata.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
76+
response = self.epidata_client.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
13477

13578
expected_values = pd.concat([values, pd.DataFrame({ "geo_type": "state", "source": "src-name", "time_type": "day", "time_value": [20200419] * 3, "signal": [signal_name] * 3, "direction": [None] * 3})], axis=1).rename(columns=uploader_column_rename).to_dict(orient="records")
13679
expected_response = {'result': 1, 'epidata': self.apply_lag(expected_values), 'message': 'success'}
@@ -158,7 +101,7 @@ def test_uploading(self):
158101

159102
# upload CSVs
160103
main(args)
161-
response = Epidata.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
104+
response = self.epidata_client.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
162105

163106
expected_values = pd.concat([values, pd.DataFrame({
164107
"geo_type": "state",
@@ -195,7 +138,7 @@ def test_uploading(self):
195138

196139
# upload CSVs
197140
main(args)
198-
response = Epidata.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
141+
response = self.epidata_client.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
199142

200143
expected_response = {'epidata': [], 'result': -2, 'message': 'no results'}
201144

@@ -220,7 +163,7 @@ def test_uploading(self):
220163

221164
# upload CSVs
222165
main(args)
223-
response = Epidata.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
166+
response = self.epidata_client.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
224167

225168
expected_values_df = pd.concat([values, pd.DataFrame({
226169
"geo_type": "state",
@@ -256,7 +199,7 @@ def test_uploading(self):
256199

257200
# upload CSVs
258201
main(args)
259-
response = Epidata.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
202+
response = self.epidata_client.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
260203

261204
expected_values = pd.concat([values, pd.DataFrame({
262205
"geo_type": "state",
@@ -290,7 +233,7 @@ def test_uploading(self):
290233

291234
# upload CSVs
292235
main(args)
293-
response = Epidata.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
236+
response = self.epidata_client.covidcast('src-name', signal_name, 'day', 'state', 20200419, '*')
294237

295238
expected_response = {'epidata': [], 'result': -2, 'message': 'no results'}
296239

integrations/acquisition/covidcast/test_delete_batch.py

Lines changed: 2 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,39 +6,16 @@
66
from os import path
77

88
# first party
9-
import delphi.operations.secrets as secrets
10-
from delphi.epidata.acquisition.covidcast.database import Database
11-
from delphi.epidata.acquisition.covidcast.test_utils import covidcast_rows_from_args
9+
from delphi.epidata.common.covidcast_test_base import covidcast_rows_from_args, CovidcastTestBase
1210

1311
# py3tester coverage target (equivalent to `import *`)
1412
__test_target__ = 'delphi.epidata.acquisition.covidcast.database'
1513

1614
Example = namedtuple("example", "given expected")
1715

18-
class DeleteBatch(unittest.TestCase):
16+
class DeleteBatch(CovidcastTestBase):
1917
"""Tests batch deletions"""
2018

21-
22-
def setUp(self):
23-
"""Perform per-test setup."""
24-
25-
# use the local instance of the epidata database
26-
secrets.db.host = 'delphi_database_epidata'
27-
secrets.db.epi = ('user', 'pass')
28-
29-
# will use secrets as set above
30-
self._db = Database()
31-
self._db.connect()
32-
33-
for table in "epimetric_load epimetric_latest epimetric_full geo_dim signal_dim".split():
34-
self._db._cursor.execute(f"TRUNCATE TABLE {table}")
35-
36-
37-
def tearDown(self):
38-
"""Perform per-test teardown."""
39-
self._db.disconnect(False)
40-
del self._db
41-
4219
@unittest.skip("Database user would require FILE privileges")
4320
def test_delete_from_file(self):
4421
self._test_delete_batch(path.join(path.dirname(__file__), "delete_batch.csv"))

0 commit comments

Comments
 (0)