def test_poll_with_fullfilment(): register_uri(POLL_URI, POLL_RESPONSE_WITH_MORE_1) client = create_client_11() gen = client.poll(POLL_COLLECTION, uri=POLL_PATH) block_1 = next(gen) assert block_1.content.decode("utf-8") == CONTENT_BLOCKS[0] message = get_sent_message() assert type(message) == tm11.PollRequest assert message.collection_name == POLL_COLLECTION responses.remove(responses.POST, POLL_URI) register_uri(POLL_URI, POLL_RESPONSE_WITH_MORE_2) block_2 = next(gen) assert block_2.content.decode("utf-8") == CONTENT_BLOCKS[1] message = get_sent_message() assert type(message) == tm11.PollFulfillmentRequest assert message.collection_name == POLL_COLLECTION assert message.result_part_number == 2
def test_bp_to_bpc(self): print("##################test from bp -> bpc####################") responses.add(responses.POST, HOST + '/v1/chain/get_producers', json=fake_json_1, status=200) responses.add(responses.POST, HOST + '/v1/chain/get_table_rows', json=fake_table_data, status=200) bp = BP("eoslemonscom", True) bp_monitor = BPMonitor(bp) bp_monitor.check_is_top21() self.assertTrue(bp.is_top21) self.assertFalse(bp.is_new_top21) responses.remove(responses.POST, HOST + '/v1/chain/get_producers') responses.add(responses.POST, HOST + '/v1/chain/get_producers', json=fake_json, status=200) responses.add(responses.POST, HOST + '/v1/chain/get_table_rows', json=fake_table_data, status=200) # be the bpc bp_monitor.check_is_top21() self.assertFalse(bp.is_top21) self.assertFalse(bp.is_new_top21) print("##################test from bp -> bpc####################\n") print("\n")
def _test_update_command(self, command_name, model_name, existing_records=1, created_records=1, skipped_records=1): # test without a file_path parameter responses.add(responses.HEAD, self.URL, headers={"Content-Length": "1024"}) responses.add(responses.GET, self.URL, body=''.join(self.DATA)) call_command(command_name) log_calls = [ mock.call('Deleting {} existing {} records'.format(existing_records, model_name)), mock.call('Parsing file'), mock.call('Creating {} {} records'.format(created_records, model_name)), mock.call('Done'), mock.call( 'Loaded {} {} records from {}. Skipped {} records with unrecognized genes.'.format( created_records, model_name, self.tmp_file, skipped_records)), mock.call('Running ./manage.py update_gencode to update the gencode version might fix missing genes') ] self.mock_logger.info.assert_has_calls(log_calls) # test with a file_path parameter self.mock_logger.reset_mock() responses.remove(responses.GET, self.URL) call_command(command_name, self.tmp_file) log_calls[0] = mock.call('Deleting {} existing {} records'.format(created_records, model_name)) self.mock_logger.info.assert_has_calls(log_calls)
def test_model_based_utf8_harvesting(app, sample_config, sample_record_xml_utf8): """Test harvesting using model encoded in utf-8.""" responses.add(responses.GET, 'http://export.arxiv.org/oai2', body=sample_record_xml_utf8, content_type='text/xml;charset=utf-8') with app.app_context(): _, records = get_records(['oai:arXiv.org:1207.1019'], name=sample_config) record = records.pop() assert record.raw.find(u'Stéphane') >= 0 responses.remove(responses.GET, 'http://export.arxiv.org/oai2') responses.add(responses.GET, 'http://export.arxiv.org/oai2', body=sample_record_xml_utf8, content_type='text/xml') with app.app_context(): _, records = get_records(['oai:arXiv.org:1207.1019'], name=sample_config, encoding='utf-8') record = records.pop() assert record.raw.find(u'Stéphane') >= 0
def run(): url = 'http://example.com/' # Adds a new response for POST responses.add( responses.POST, url, json={'foo': 'bar'}, status=201 ) # A new response for the same URL but for GET responses.add( responses.GET, url, json={'foo': 'baz'}, status=200 ) # Removes the URL for POST (because I might want to replace its # response for something else responses.remove(responses.POST, url) # It should be possible to make a GET request resp = requests.get(url) assert resp.json()['foo'] == 'baz' # But a POST request should not be possible with pytest.raises(ConnectionError): resp = requests.post(url)
def wrapper(*args, **kwargs): responses.add(method=method, url=url, json=json, body=body, status=status) result = func(*args, **kwargs) responses.remove(method, url) return result
def test_httpclient_raises_for_non_2xx_status(): statuses = [400, 403, 404, 500, 501, 502] # sample non 2xx statuses client = HttpClient("token", "https://domain.com") for status in statuses: responses.add(responses.GET, "https://domain.com/get", status=status) with pytest.raises(HttpError): res = client.send_request("GET", "get") responses.remove(responses.GET, "https://domain.com/get")
def test_update_mgi_command(self, mock_tempfile, mock_logger): tmp_dir = tempfile.gettempdir() mock_tempfile.gettempdir.return_value = tmp_dir tmp_file = '{}/HMD_HumanPhenotype.rpt'.format(tmp_dir) # test without a file_path parameter url = 'http://www.informatics.jax.org/downloads/reports/HMD_HumanPhenotype.rpt' responses.add(responses.HEAD, url, headers={"Content-Length": "1024"}) responses.add(responses.GET, url, body=''.join(MGI_DATA)) call_command('update_mgi') calls = [ mock.call('Deleting 0 existing MGI records'), mock.call('Parsing file'), mock.call('Creating 2 MGI records'), mock.call('Done'), mock.call( 'Loaded 2 MGI records from {}. Skipped 2 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_logger.info.assert_has_calls(calls) # test with a file_path parameter responses.remove(responses.GET, url) mock_logger.reset_mock() call_command('update_mgi', tmp_file) calls = [ mock.call('Deleting 2 existing MGI records'), mock.call('Parsing file'), mock.call('Creating 2 MGI records'), mock.call('Done'), mock.call( 'Loaded 2 MGI records from {}. Skipped 2 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_logger.info.assert_has_calls(calls) self.assertEqual(MGI.objects.all().count(), 2) record = MGI.objects.get(gene__gene_id='ENSG00000223972') self.assertEqual(record.marker_id, 'MGI:2152878') # Test exception with no dbNSFPGene records dbNSFPGene.objects.all().delete() with self.assertRaises(CommandError) as ce: call_command('update_mgi') self.assertEqual( str(ce.exception), 'dbNSFPGene table is empty. Run \'./manage.py update_dbnsfp_gene\' before running this command.' )
def test_update_gene_constraint_command(self, mock_tempfile, mock_logger): tmp_dir = tempfile.gettempdir() mock_tempfile.gettempdir.return_value = tmp_dir tmp_file = '{}/gnomad.v2.1.1.lof_metrics.by_gene.txt'.format(tmp_dir) # test without a file_path parameter url = 'http://storage.googleapis.com/seqr-reference-data/gene_constraint/gnomad.v2.1.1.lof_metrics.by_gene.txt' responses.add(responses.HEAD, url, headers={"Content-Length": "1024"}) responses.add(responses.GET, url, body=''.join(GNOMAD_LOF_METRICS_DATA)) call_command('update_gene_constraint') calls = [ mock.call('Deleting 1 existing GeneConstraint records'), mock.call('Parsing file'), mock.call('Creating 2 GeneConstraint records'), mock.call('Done'), mock.call( 'Loaded 2 GeneConstraint records from {}. Skipped 1 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_logger.info.assert_has_calls(calls) # test with a file_path parameter mock_logger.reset_mock() responses.remove(responses.GET, url) call_command('update_gene_constraint', tmp_file) calls = [ mock.call('Deleting 2 existing GeneConstraint records'), mock.call('Parsing file'), mock.call('Creating 2 GeneConstraint records'), mock.call('Done'), mock.call( 'Loaded 2 GeneConstraint records from {}. Skipped 1 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_logger.info.assert_has_calls(calls) self.assertEqual(GeneConstraint.objects.count(), 2) record = GeneConstraint.objects.get(gene__gene_id='ENSG00000237683') self.assertEqual(record.mis_z, -0.7773) self.assertEqual(record.mis_z_rank, 1) self.assertEqual(record.louef, 1.606) self.assertEqual(record.louef_rank, 0) self.assertEqual(record.pLI, 0.00090576) self.assertEqual(record.pLI_rank, 1)
def test_update_hpo_command(self, mock_tempfile, mock_logger): tmp_dir = tempfile.gettempdir() mock_tempfile.gettempdir.return_value = tmp_dir tmp_file = '{}/hp.obo'.format(tmp_dir) url = 'http://purl.obolibrary.org/obo/hp.obo' responses.add(responses.HEAD, url, headers={"Content-Length": "1024"}) responses.add(responses.GET, url, body=''.join(PHO_DATA[:40])) responses.add(responses.GET, url, body=''.join(PHO_DATA)) # test data which causes exception (missing parent hpo id) with self.assertRaises(ValueError) as ve: call_command('update_human_phenotype_ontology') self.assertEqual(str(ve.exception), "Strange id: HP:0000003") # test without a file_path parameter call_command('update_human_phenotype_ontology') calls = [ mock.call( 'Deleting HumanPhenotypeOntology table with 11 records and creating new table with 5 records' ), mock.call('Done'), ] mock_logger.info.assert_has_calls(calls) # test with a hpo_file_path parameter responses.remove(responses.GET, url) mock_logger.reset_mock() call_command('update_human_phenotype_ontology', tmp_file) calls = [ mock.call( 'Deleting HumanPhenotypeOntology table with 5 records and creating new table with 5 records' ), mock.call('Done'), ] mock_logger.info.assert_has_calls(calls) records = { record.hpo_id: { 'is_category': record.is_category, 'definition': record.definition, 'name': record.name, 'parent_id': record.parent_id, 'hpo_id': record.hpo_id, 'category_id': record.category_id } for record in HumanPhenotypeOntology.objects.all() } self.assertDictEqual(records, EXPECTED_DB_DATA)
def test_update_primate_ai_command(self, mock_tempfile, mock_logger): tmp_dir = tempfile.gettempdir() mock_tempfile.gettempdir.return_value = tmp_dir tmp_file = '{}/Gene_metrics_clinvar_pcnt.cleaned_v0.2.txt'.format( tmp_dir) # test without a file_path parameter url = 'http://storage.googleapis.com/seqr-reference-data/primate_ai/Gene_metrics_clinvar_pcnt.cleaned_v0.2.txt' responses.add(responses.HEAD, url, headers={"Content-Length": "1024"}) responses.add(responses.GET, url, body=''.join(PRIMATE_AI_DATA)) call_command('update_primate_ai') calls = [ mock.call('Deleting 1 existing PrimateAI records'), mock.call('Parsing file'), mock.call('Creating 2 PrimateAI records'), mock.call('Done'), mock.call( 'Loaded 2 PrimateAI records from {}. Skipped 2 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_logger.info.assert_has_calls(calls) # test with a file_path parameter responses.remove(responses.GET, url) mock_logger.reset_mock() call_command('update_primate_ai', tmp_file) calls = [ mock.call('Deleting 2 existing PrimateAI records'), mock.call('Parsing file'), mock.call('Creating 2 PrimateAI records'), mock.call('Done'), mock.call( 'Loaded 2 PrimateAI records from {}. Skipped 2 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_logger.info.assert_has_calls(calls) self.assertEqual(PrimateAI.objects.all().count(), 2) record = PrimateAI.objects.get(gene__gene_id='ENSG00000235249') self.assertEqual(record.percentile_25, 0.383666202) self.assertEqual(record.percentile_75, 0.593389094)
def test_uc_server_error_recovery(unleash_client): # Verify that Unleash Client will still fall back gracefully if SERVER ANGRY RAWR, and then recover gracefully. unleash_client = unleash_client # Set up APIs responses.add(responses.POST, URL + REGISTER_URL, json={}, status=401) responses.add(responses.GET, URL + FEATURES_URL, status=500) responses.add(responses.POST, URL + METRICS_URL, json={}, status=401) unleash_client.initialize_client() assert not unleash_client.is_enabled("testFlag") responses.remove(responses.GET, URL + FEATURES_URL) responses.add(responses.GET, URL + FEATURES_URL, json=MOCK_FEATURE_RESPONSE, status=200) time.sleep(20) assert unleash_client.is_enabled("testFlag")
def test_update_dbnsfp_gene_command(self, mock_tempfile, mock_logger): tmp_dir = tempfile.gettempdir() mock_tempfile.gettempdir.return_value = tmp_dir tmp_file = '{}/dbNSFP4.0_gene'.format(tmp_dir) url = 'http://storage.googleapis.com/seqr-reference-data/dbnsfp/dbNSFP4.0_gene' responses.add(responses.HEAD, url, headers={"Content-Length": "1024"}) responses.add(responses.GET, url, body=''.join(dbNSFP_GENE_DATA)) # test without a file_path parameter call_command('update_dbnsfp_gene') calls = [ mock.call('Deleting 3 existing dbNSFPGene records'), mock.call('Parsing file'), mock.call('Creating 1 dbNSFPGene records'), mock.call('Done'), mock.call( 'Loaded 1 dbNSFPGene records from {}. Skipped 1 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_logger.info.assert_has_calls(calls) self.assertEqual(dbNSFPGene.objects.count(), 1) record = dbNSFPGene.objects.get(gene_names='OR4F5') self.assertEqual(record.gene.gene_id, 'ENSG00000186092') # test with a file_path parameter mock_logger.reset_mock() responses.remove(responses.GET, url) call_command('update_dbnsfp_gene', tmp_file) calls = [ mock.call('Deleting 1 existing dbNSFPGene records'), mock.call('Parsing file'), mock.call('Creating 1 dbNSFPGene records'), mock.call('Done'), mock.call( 'Loaded 1 dbNSFPGene records from {}. Skipped 1 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_logger.info.assert_has_calls(calls)
def test_mantis_csv_file_other_http_errors(self): # If the Mantis server returns other HTTP errors than 500, # they appear as BugTrackerConnectErrors. responses.add('POST', 'http://mantis.example.com/view_all_set.php', status=200) responses.add('GET', 'http://mantis.example.com/csv_export.php', status=503) tracker = Mantis('http://mantis.example.com') self.assertRaises(BugTrackerConnectError, tracker._csv_data) responses.remove('GET', 'http://mantis.example.com/csv_export.php') responses.add('GET', 'http://mantis.example.com/csv_export.php', status=404) self.assertRaises(BugTrackerConnectError, tracker._csv_data)
def _consultar(self, caso): with self.subTest(caso['nome']): responses.add(caso['metodo'], _ENDERECO_NEO4J % caso['endereco'], json=caso['resposta']) resposta = self.app.get(caso['servico'], query_string=caso['query_string']) assert resposta.get_json() == caso['resposta'] if caso['query_string']: assert json.loads( responses.calls[-1].request.body) == caso['requisicao'] else: assert responses.calls[-1].request.body is None responses.remove(caso['metodo'], _ENDERECO_NEO4J % caso['endereco'])
def test_run_on_cond(self, test_instance, local_context, graphql_url, capsys): test_id = 0 test = TestSessions.create_instance(test_id, Test_Sessions.config, self.args) test.create_output_instance() responses.add(responses.POST, graphql_url, json=pytest_common.assets, status=200) router_context = RouterContext.create_instance(local_context, self.args.router, self.args) router_context = RouterContext.create_instance(local_context, "SITE0001P1", self.args, pytest_common.assets[0]) router_context.update(pytest_common.assets[1]) # Note if test.run uses more than one call to the graphql API, responses.remove() # and responses.add() cannot properly satisfy different requests to the same url responses.remove(responses.POST, graphql_url) responses.add(responses.POST, graphql_url, json=test_instance["json_reply"], status=200) test.run(local_context, router_context, None, fp=None) captured = capsys.readouterr() all_lines = captured.out.splitlines() assert len(all_lines[0]) == len(test_instance["message"]) assert all_lines[0] == test_instance["message"]
def test_get_iap_public_key_cache_refresh(): # Given responses.add(responses.GET, 'https://www.gstatic.com/iap/verify/public_key', body=json.dumps({'key_1': 'dummy_1'})) # We get the first key to cache the result get_iap_public_key('key_1') # Add another key to the response responses.remove(responses.GET, 'https://www.gstatic.com/iap/verify/public_key') responses.add(responses.GET, 'https://www.gstatic.com/iap/verify/public_key', body=json.dumps({ 'key_1': 'dummy_1', 'key_2': 'dummy_2' })) # When we get the second key actual_key_2 = get_iap_public_key('key_2') # Then the cache is refreshed so the second key can be accessed unittest_helper.assertEqual(actual_key_2, 'dummy_2')
def run(): responses.add(responses.GET, "http://example.com/zero") responses.add(responses.GET, "http://example.com/one") responses.add(responses.GET, "http://example.com/two") responses.add(responses.GET, re.compile(r"http://example\.com/three")) responses.add(responses.GET, re.compile(r"http://example\.com/four")) re.purge() responses.remove(responses.GET, "http://example.com/two") responses.remove(Response(method=responses.GET, url="http://example.com/zero")) responses.remove(responses.GET, re.compile(r"http://example\.com/four")) with pytest.raises(ConnectionError): requests.get("http://example.com/zero") requests.get("http://example.com/one") with pytest.raises(ConnectionError): requests.get("http://example.com/two") requests.get("http://example.com/three") with pytest.raises(ConnectionError): requests.get("http://example.com/four")
def run(): responses.add(responses.GET, 'http://example.com/zero') responses.add(responses.GET, 'http://example.com/one') responses.add(responses.GET, 'http://example.com/two') responses.add(responses.GET, re.compile(r'http://example\.com/three')) responses.add(responses.GET, re.compile(r'http://example\.com/four')) re.purge() responses.remove(responses.GET, 'http://example.com/two') responses.remove( Response(method=responses.GET, url='http://example.com/zero')) responses.remove(responses.GET, re.compile(r'http://example\.com/four')) with pytest.raises(ConnectionError): requests.get('http://example.com/zero') requests.get('http://example.com/one') with pytest.raises(ConnectionError): requests.get('http://example.com/two') requests.get('http://example.com/three') with pytest.raises(ConnectionError): requests.get('http://example.com/four')
def test_update_omim_command(self, mock_os, mock_tempfile, mock_omim_logger, mock_utils_logger): tmp_dir = tempfile.gettempdir() mock_tempfile.gettempdir.return_value = tmp_dir tmp_file = '{}/genemap2.txt'.format(tmp_dir) data_url = 'https://data.omim.org/downloads/test_key/genemap2.txt' responses.add(responses.HEAD, data_url, headers={"Content-Length": "1024"}) responses.add(responses.GET, data_url, body=''.join(OMIM_DATA)) # Test omim api response error responses.add( responses.GET, 'https://api.omim.org/api/entry?apiKey=test_key&include=geneMap&format=json&mimNumber=612367', json={'error': 'not found'}, status=400) # Test omim api responses with bad data responses.add( responses.GET, 'https://api.omim.org/api/entry?apiKey=test_key&include=geneMap&format=json&mimNumber=612367', json={"omim": { "entryList": [] }}, status=200) # Normal omim api responses responses.add( responses.GET, 'https://api.omim.org/api/entry?apiKey=test_key&include=geneMap&format=json&mimNumber=612367', json=OMIM_ENTRIES, status=200) # Omim api response error test with self.assertRaises(CommandError) as ce: call_command('update_omim', '--omim-key=test_key') self.assertEqual(str(ce.exception), 'Request failed with 400: Bad Request') # Bad omim api response test with self.assertRaises(CommandError) as ce: call_command('update_omim', '--omim-key=test_key') self.assertEqual(str(ce.exception), 'Expected 1 omim entries but recieved 0') # Test without a file_path parameter mock_utils_logger.reset_mock() call_command('update_omim', '--omim-key=test_key') calls = [ mock.call('Deleting 0 existing Omim records'), mock.call('Parsing file'), mock.call('Creating 2 Omim records'), mock.call('Done'), mock.call( 'Loaded 2 Omim records from {}. Skipped 2 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_utils_logger.info.assert_has_calls(calls) calls = [ mock.call('Adding phenotypic series information'), mock.call('Found 1 records with phenotypic series') ] mock_omim_logger.info.assert_has_calls(calls) mock_omim_logger.debug.assert_called_with('Fetching entries 0-20') mock_os.system.assert_not_called() # test with a file_path parameter responses.remove(responses.GET, data_url) mock_utils_logger.reset_mock() mock_omim_logger.reset_mock() call_command('update_omim', '--omim-key=test_key', '--cache-parsed-records', tmp_file) calls = [ mock.call('Deleting 2 existing Omim records'), mock.call('Parsing file'), mock.call('Creating 2 Omim records'), mock.call('Done'), mock.call( 'Loaded 2 Omim records from {}. Skipped 2 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_utils_logger.info.assert_has_calls(calls) calls = [ mock.call('Adding phenotypic series information'), mock.call('Found 1 records with phenotypic series'), mock.call( 'gsutil mv parsed_omim_records.txt gs://seqr-reference-data/omim/' ), ] mock_omim_logger.info.assert_has_calls(calls) mock_omim_logger.debug.assert_called_with('Fetching entries 0-20') mock_os.system.assert_called_with( 'gsutil mv parsed_omim_records.txt gs://seqr-reference-data/omim/') with open('parsed_omim_records.txt', 'r') as f: self.assertEqual(f.read(), CACHED_OMIM_DATA) self._assert_has_expected_omim_records()
def test_update_omim_command(self, mock_tempfile, mock_omim_logger, mock_utils_logger): tmp_dir = tempfile.gettempdir() mock_tempfile.gettempdir.return_value = tmp_dir tmp_file = '{}/genemap2.txt'.format(tmp_dir) data_url = 'https://data.omim.org/downloads/test_key/genemap2.txt' responses.add(responses.HEAD, data_url, headers={"Content-Length": "1024"}) responses.add(responses.GET, data_url, body=''.join(OMIM_DATA)) # Test omim api response error responses.add( responses.GET, 'https://api.omim.org/api/entry?apiKey=test_key&include=geneMap&format=json&mimNumber=612367', json={'error': 'not found'}, status=400) # Test omim api responses with bad data responses.add( responses.GET, 'https://api.omim.org/api/entry?apiKey=test_key&include=geneMap&format=json&mimNumber=612367', json={"omim": { "entryList": [] }}, status=200) # Normal omim api responses responses.add( responses.GET, 'https://api.omim.org/api/entry?apiKey=test_key&include=geneMap&format=json&mimNumber=612367', json=OMIM_ENTRIES, status=200) # Omim api response error test with self.assertRaises(CommandError) as ce: call_command('update_omim', '--omim-key=test_key') self.assertEqual(str(ce.exception), 'Request failed with 400: Bad Request') # Bad omim api response test with self.assertRaises(CommandError) as ce: call_command('update_omim', '--omim-key=test_key') self.assertEqual(str(ce.exception), 'Expected 1 omim entries but recieved 0') # Test without a file_path parameter mock_utils_logger.reset_mock() call_command('update_omim', '--omim-key=test_key') calls = [ mock.call('Deleting 0 existing Omim records'), mock.call('Parsing file'), mock.call('Creating 2 Omim records'), mock.call('Done'), mock.call( 'Loaded 2 Omim records from {}. Skipped 2 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_utils_logger.info.assert_has_calls(calls) calls = [ mock.call('Adding phenotypic series information'), mock.call('Found 1 records with phenotypic series') ] mock_omim_logger.info.assert_has_calls(calls) mock_omim_logger.debug.assert_called_with('Fetching entries 0-20') # test with a file_path parameter responses.remove(responses.GET, data_url) mock_utils_logger.reset_mock() mock_omim_logger.reset_mock() call_command('update_omim', '--omim-key=test_key', tmp_file) calls = [ mock.call('Deleting 2 existing Omim records'), mock.call('Parsing file'), mock.call('Creating 2 Omim records'), mock.call('Done'), mock.call( 'Loaded 2 Omim records from {}. Skipped 2 records with unrecognized genes.' .format(tmp_file)), mock.call( 'Running ./manage.py update_gencode to update the gencode version might fix missing genes' ) ] mock_utils_logger.info.assert_has_calls(calls) calls = [ mock.call('Adding phenotypic series information'), mock.call('Found 1 records with phenotypic series') ] mock_omim_logger.info.assert_has_calls(calls) mock_omim_logger.debug.assert_called_with('Fetching entries 0-20') self.assertEqual(Omim.objects.all().count(), 2) record = Omim.objects.get(gene__gene_symbol='OR4F5') self.assertEqual(record.comments, 'linkage with rs1780324') self.assertEqual(record.gene_description, 'Alkaline phosphatase, plasma level of, QTL 2') self.assertEqual(record.mim_number, 612367) self.assertEqual(record.phenotype_description, 'Alkaline phosphatase, plasma level of, QTL 2') self.assertEqual(record.phenotype_inheritance, None) self.assertEqual(record.phenotype_map_method, '2') self.assertEqual(record.phenotype_mim_number, 612367) self.assertEqual(record.phenotypic_series_number, 'PS300755')
def test_get_api_key(): event_loop = asyncio.get_event_loop() with assert_raises(requests.exceptions.ConnectionError): OP = OctoPrint('127.0.0.1', 1) try: event_loop.run_until_complete(OP.get_api_key('test', None, 1)) finally: #event_loop.close() pass with assert_raises(requests.exceptions.ConnectionError): OP = OctoPrint('127.0.0.2', 1) try: event_loop.run_until_complete(OP.get_api_key('test', None, 1)) finally: #event_loop.close() pass OP = OctoPrint('mock', 1) responses.add(responses.GET, 'http://mock:1/plugin/appkeys/probe', json={}, status=404) with assert_raises(Exception): try: event_loop.run_until_complete(OP.get_api_key('test', None, 1)) finally: #event_loop.close() pass responses.replace(responses.GET, 'http://mock:1/plugin/appkeys/probe', json={}, status=204) def request_callback_fail(request): return (404, {}, json.dumps({})) responses.add_callback( responses.POST, 'http://mock:1/plugin/appkeys/request', callback=request_callback_fail, content_type='application/json', ) with assert_raises(Exception): try: event_loop.run_until_complete(OP.get_api_key('test', None, 1)) finally: #event_loop.close() pass def request_callback_successs(request): return (201, {}, json.dumps({'app_token': 'abc'})) responses.remove(responses.POST, 'http://mock:1/plugin/appkeys/request') responses.add_callback( responses.POST, 'http://mock:1/plugin/appkeys/request', callback=request_callback_successs, content_type='application/json', ) with assert_raises(Exception): try: event_loop.run_until_complete(OP.get_api_key('test', None, 1)) finally: #event_loop.close() pass responses.add(responses.GET, 'http://mock:1/plugin/appkeys/request/abc', json={}, status=202) responses.add(responses.GET, 'http://mock:1/plugin/appkeys/request/abc', json={}, status=404) with assert_raises(Exception): try: event_loop.run_until_complete(OP.get_api_key('test', None, 1)) finally: #event_loop.close() pass responses.remove(responses.GET, 'http://mock:1/plugin/appkeys/request/abc') responses.add(responses.GET, 'http://mock:1/plugin/appkeys/request/abc', json={}, status=202) responses.add(responses.GET, 'http://mock:1/plugin/appkeys/request/abc', json={'api_key': 'secretkey'}, status=200) try: assert event_loop.run_until_complete(OP.get_api_key('test', None, 1)) == True finally: #event_loop.close() pass
def tearDown(self): responses.remove(responses.POST, HOST + '/v1/chain/get_producers') responses.remove(responses.GET, HOST + '/v1/chain/get_info') responses.remove(responses.POST, HOST + '/v1/chain/get_table_rows')