def test_unnecessary_specification_url(self): spec_url = "http://localhost:8000/docs/openapi.json" session = DesignRuleSessionFactory(test_suite__api_endpoint="http://localhost:8000/api/v1", test_version=self.test_version) with requests_mock.Mocker() as mock: dir_path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(dir_path, "files", "good.json")) as html_file: # The OAS file is also served on the expected path, # so api_51_20200709 should succeed and give us full points mock.get('http://localhost:8000/api/v1/openapi.json', text=html_file.read(), headers={"Access-Control-Allow-Origin": "http://foo.example"}) mock.get('http://localhost:8000/api/v1/openapi.yaml', status_code=404) mock.get(spec_url, text=html_file.read(), headers={"Access-Control-Allow-Origin": "http://foo.example"}) mock.get('http://localhost:8000/api/v1/designrule-session/', status_code=404) mock.get('http://localhost:8000/api/v1/designrule-session/%7Buuid%7D/', status_code=404) mock.get('http://localhost:8000/api/v1/designrule-session/shield/%7Buuid%7D/', status_code=404) mock.get('http://localhost:8000/api/v1/designrule-testsuite/', status_code=404) mock.post('http://localhost:8000/api/v1/designrule-testsuite/', status_code=404) mock.get('http://localhost:8000/api/v1/designrule-testsuite/%7Buuid%7D/', status_code=404) mock.post('http://localhost:8000/api/v1/designrule-testsuite/%7Buuid%7D/start_session/', status_code=404) run_tests(session, "http://localhost:8000/api/v1", spec_url) self.assertEqual(DesignRuleResult.objects.count(), 7) session.refresh_from_db() self.assertTrue(session.successful()) self.assertEqual(session.percentage_score, Decimal("100"))
def code2user_info(self, code=None, access_token=None, openid=None, auth_type='marketer'): auth_url_map = { # 'marketer': '/api/marketer/get-marketer-wechat-info/', 'marketer': reverse('get-marketer-wechat-info'), # 'merchant': '/api/marketer/get-merchant-wechat-info/' 'merchant': reverse('get-merchant-wechat-info') } pattern_get_access_token = re.compile( r'^https://api\.weixin\.qq\.com/sns/oauth2/access_token?[\w\W]*') pattern_get_use_info = re.compile(r'^https://api\.weixin\.qq\.com/sns/userinfo?[\w\W]*') get_access_token_callback = WXWebCode2AccessTokenCallback(code=self.code) self.access_token = get_access_token_callback.mock_success()['access_token'] self.openid = get_access_token_callback.mock_success()['openid'] get_user_info_callback = WXAccessToken2InfoCallback( access_token=access_token or self.access_token, openid=openid or self.openid) with requests_mock.Mocker(real_http=False) as m: m.register_uri('GET', pattern_get_access_token, json=get_access_token_callback.mock_callback) m.register_uri('GET', pattern_get_use_info, json=get_user_info_callback.mock_callback) url = auth_url_map[auth_type] return self.client.get(url, data={'code': code or self.code, 'state': self.state})
def test_url_command(): """ Given: - url When: - running url command and validate whether the url is malicious Then: - return command results containing indicator and dbotscore """ url = 'https://test.com/rest/threatindicator/v0/url?key.values=http://www.malware.com' status_code = 200 json_data = URL_RES_JSON expected_output = { 'URL': [{ 'Data': 'http://www.malware.com' }], 'DBOTSCORE': [{ 'Indicator': 'http://www.malware.com', 'Type': 'url', 'Vendor': 'iDefense', 'Score': 2 }] } url_to_check = {'url': 'http://www.malware.com'} with requests_mock.Mocker() as m: m.get(url, status_code=status_code, json=json_data) client = Client(API_URL, 'api_token', True, False) results = url_command(client, url_to_check) output = results[0].to_context().get('EntryContext', {}) assert output.get('URL(val.Data && val.Data == obj.Data)', []) == expected_output.get('URL') assert output.get(DBOT_KEY, []) == expected_output.get('DBOTSCORE')
def test_images_options_newer_proxy(proxy_server, signed_ticket): auth.add_signed_ticket(signed_ticket.data) path = "/images/" + signed_ticket.id # Note: the daemon does not report GET since the ticket is write only, and # it supports only "zero" (simulating old daemon). daemon_allow = {"OPTIONS", "PUT", "PATCH"} daemon_features = {"zero"} daemon_options = {"features": list(daemon_features)} daemon_body = json.dumps(daemon_options).encode("ascii") daemon_headers = { "Content-Type": "application/json", "Content-Length": "%d" % len(daemon_body), "Allow": ','.join(daemon_allow) } with requests_mock.Mocker() as m: m.options(requests_mock.ANY, status_code=200, text=daemon_body, headers=daemon_headers) res = http.request(proxy_server, "OPTIONS", path) # Validate the request. assert m.called assert m.last_request.path == path conn_timeout, read_timeout = m.last_request.timeout assert conn_timeout == proxy_server.imaged_connection_timeout_sec assert read_timeout == proxy_server.imaged_read_timeout_sec # Validate the response. assert res.status == 200 assert set(res.getheader("Allow").split(",")) == daemon_allow assert set(json.loads(res.read())["features"]) == daemon_features
def test_images_cors_options(proxy_server, signed_ticket): auth.add_signed_ticket(signed_ticket.data) request_headers = images_request_headers(signed_ticket.data) path = "/images/" + signed_ticket.id daemon_options = {"features": ["zero"]} daemon_body = json.dumps(daemon_options).encode("ascii") daemon_headers = { "Content-Type": "application/json", "Content-Length": "%d" % len(daemon_body), "Allow": "GET,PUT,PATCH,OPTIONS" } with requests_mock.Mocker() as m: m.options(requests_mock.ANY, status_code=200, text=daemon_body, headers=daemon_headers) res = http.request(proxy_server, "OPTIONS", path, headers=request_headers) assert m.called allowed_headers = split_header( res.getheader("access-control-allow-headers")) expected_headers = { "cache-control", "pragma", "authorization", "content-type", "content-length", "content-range", "range", "session-id" } assert res.status == 200 assert allowed_headers == expected_headers assert res.getheader("access-control-allow-origin") == "*" assert res.getheader("access-control-max-age") == "300"
def mediawiki(): def post_token(request, context): authorization_header = request.headers['Authorization'].decode('utf8') request_nonce = re.search(r'oauth_nonce="(.*?)"', authorization_header).group(1) return jwt.encode( { 'username': '******', 'aud': 'client_id', 'iss': 'https://meta.wikimedia.org', 'iat': time.time(), 'nonce': request_nonce, }, 'client_secret') with requests_mock.Mocker() as mock: mock.post( '/w/index.php?title=Special%3AOAuth%2Finitiate', text='oauth_token=key&oauth_token_secret=secret', ) mock.post('/w/index.php?title=Special%3AOAuth%2Ftoken', text='oauth_token=key&oauth_token_secret=secret') mock.post('/w/index.php?title=Special%3AOAuth%2Fidentify', content=post_token) yield mock
def create( crawler, record=JohnDoe.RECORD_WITH_CLOSED_CASES, cases={ 'X0001': CaseDetails.case_x(), 'X0002': CaseDetails.case_x(), 'X0003': CaseDetails.case_x() }): base_url = 'https://publicaccess.courts.oregon.gov/PublicAccessLogin/' with requests_mock.Mocker() as m: m.post("{}{}".format(base_url, 'Search.aspx?ID=100'), [{ 'text': SearchPageResponse.RESPONSE }, { 'text': record }]) for key, value in cases.items(): m.get("{}{}{}".format(base_url, 'CaseDetail.aspx?CaseID=', key), text=value) return crawler.search('John', 'Doe')
def test_success_posted_to_secure_callback_url(test_scheduler): """If an entry has callback_url defined, scheduler should POST to it.""" cb_flag = threading.Event() def cb_request_handler(sess, resp): cb_flag.set() cb, action_flag = create_action() # less priority to force run after bad_entry fails schedule_entry = create_entry( "t", 20, None, None, None, cb.__name__, "mock://cburl" ) token = schedule_entry.owner.auth_token s = test_scheduler advance_testclock(s.timefn, 1) s._callback_response_handler = cb_request_handler assert not action_flag.is_set() request_json = None with requests_mock.Mocker() as m: m.post( "mock://cburl", request_headers={"Authorization": "Token " + str(token)} ) # register mock url for posting s.run(blocking=False) time.sleep(0.1) # let requests thread run request_json = m.request_history[0].json() assert cb_flag.is_set() assert action_flag.is_set() assert request_json["status"] == "success" assert request_json["task_id"] == 1 assert request_json["self"] assert request_json["started"] assert request_json["finished"] assert request_json["duration"]
def test_alter_retention_policy(self): """Test alter retention policy for TestInfluxDBClient object.""" example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri(requests_mock.GET, "http://localhost:8086/query", text=example_response) # Test alter duration self.cli.alter_retention_policy('somename', 'db', duration='4d') self.assertEqual( m.last_request.qs['q'][0], 'alter retention policy "somename" on "db" duration 4d') # Test alter replication self.cli.alter_retention_policy('somename', 'db', replication=4) self.assertEqual( m.last_request.qs['q'][0], 'alter retention policy "somename" on "db" replication 4') # Test alter default self.cli.alter_retention_policy('somename', 'db', default=True) self.assertEqual( m.last_request.qs['q'][0], 'alter retention policy "somename" on "db" default')
def test_request_quay_authenticate_success(mock_authenticate): with requests_mock.Mocker() as m: m.get( "https://quay.io/v2/get/data/1", [ { "headers": { "some-header": "value" }, "status_code": 401 }, { "text": "data", "status_code": 200 }, ], ) client = quay_client.QuayClient("user", "pass") r = client._request_quay("GET", "get/data/1") assert r.text == "data" assert r.status_code == 200 mock_authenticate.assert_called_once_with({"some-header": "value"})
def test_authenticator_should_refresh_token_rightly(): with requests_mock.Mocker() as mock: valid_url = "mock://valid-url-test.occa.ocs.oraclecloud.com" valid_token = "eyJhbGciOiJSUzI1NiIsSI6InA3OTA3OTE4YzYiLCJraWQiOiIwDVjWxsLCJ4NXUiOiJodHL3" response_login = { "access_token": "R4ND0M", "token_type": "bearer", "expires_in": 11 } response_refresh = { "access_token": "R4ND0M11", "token_type": "bearer", "expires_in": 11 } mock.post(f'{valid_url}/ccadmin/v1/login', json=response_login) mock.post(f'{valid_url}/ccadmin/v1/refresh', json=response_refresh) authentication = OccAuthenticator(valid_url, valid_token) first_token = authentication.session.headers.get('Authorization') sleep(2) second_token = authentication.session.headers.get('Authorization') assert response_login.get("access_token") in first_token assert response_refresh.get("access_token") in second_token assert first_token != second_token
def test_einddatum_bekend_irrelevant(self): # For afgehandeld & termijn, the value of the checkbox doesn't matter, # so it may not be set to True. procestype = PROCESTYPE_URL.format( uuid='e1b73b12-b2f6-4c4e-8929-94f84dd2a57d') resultaat_url = RESULTAAT_URL.format( uuid='ebe82547-609d-464d-875e-7088bf5dc8aa') zaaktype = ZaakTypeFactory.create(selectielijst_procestype=procestype) pairs = ( ('nihil', Afleidingswijze.afgehandeld), ('ingeschatte_bestaansduur_procesobject', Afleidingswijze.termijn), ) for procestermijn, afleidingswijze in pairs: with self.subTest(afleidingswijze=afleidingswijze): with requests_mock.Mocker() as m: m.register_uri('GET', resultaat_url, json={ 'url': resultaat_url, 'procesType': procestype, 'procestermijn': procestermijn, }) form = self._get_form( afleidingswijze, zaaktype, resultaat_url, **{ 'brondatum_archiefprocedure_einddatum_bekend': True }) self.assertFalse(form.is_valid()) errors = form.errors.as_data() self.assertEqual( errors['brondatum_archiefprocedure_einddatum_bekend'] [0].code, 'invalid')
def test_iibbuilddetails_pager( fixture_builds_page1_json, fixture_builds_page2_json, fixture_build_details_json, fixture_build_details_json2, ): with requests_mock.Mocker() as m: m.register_uri( "GET", "/api/v1/builds", status_code=200, json=fixture_builds_page1_json ) m.register_uri( "GET", "/api/v1/builds?page=2", status_code=200, json=fixture_builds_page2_json, ) m.register_uri( "GET", "/api/v1/builds?page=1", status_code=200, json=fixture_builds_page1_json, ) iibc = IIBClient("fake-host") pager = iibc.get_builds() assert pager.items() == [ IIBBuildDetailsModel.from_dict(fixture_builds_page1_json["items"][0]) ] pager.next() assert pager.items() == [ IIBBuildDetailsModel.from_dict(fixture_builds_page2_json["items"][0]) ] pager.prev() assert pager.items() == [ IIBBuildDetailsModel.from_dict(fixture_builds_page1_json["items"][0]) ]
def test_cbr_fetcher(): with requests_mock.Mocker() as m: m.get(CBRFetcher.url, text=_get_xml_response()) cbr_fetcher = CBRFetcher() currency_rates = cbr_fetcher.currency_rates() expected = { "AUD": { "code": "AUD", "name": "Австралийский доллар", "rate": 45.8946 }, "AZN": { "code": "AZN", "name": "Азербайджанский манат", "rate": 37.8675 }, "GBP": { "code": "GBP", "name": "Фунт стерлингов Соединенного королевства", "rate": 84.0738, }, } assert expected == currency_rates
def test_start_scan_bad_resp(self): """Testing the start scan command successfully.""" scan_out = StringIO() url_get_source = BASE_URL + SOURCE_URI + '?name=source1' url_post = BASE_URL + SCAN_URI source_data = [{ 'id': 1, 'name': 'source1', 'hosts': ['1.2.3.4'], 'credentials': [{ 'id': 2, 'name': 'cred2' }] }] with requests_mock.Mocker() as mocker: mocker.get(url_get_source, status_code=500, json=source_data) mocker.post(url_post, status_code=201, json={'id': 1}) ssc = ScanStartCommand(SUBPARSER) args = Namespace(sources=['source1'], max_concurrency=4) with self.assertRaises(SystemExit): with redirect_stdout(scan_out): ssc.main(args) self.assertTrue('Source "source_none" does not exist' in scan_out.getvalue())
def test_show_cred_data(self): """Testing the show credential command with stubbed data.""" cred_out = StringIO() url = get_server_location() + CREDENTIAL_URI + '?name=cred1' credential_entry = { 'id': 1, 'name': 'cred1', 'username': '******', 'password': '******' } results = [credential_entry] data = {'count': 1, 'results': results} with requests_mock.Mocker() as mocker: mocker.get(url, status_code=200, json=data) asc = CredShowCommand(SUBPARSER) args = Namespace(name='cred1') with redirect_stdout(cred_out): asc.main(args) expected = '{"id":1,"name":"cred1","password":"******",' \ '"username":"******"}' self.assertEqual( cred_out.getvalue().replace('\n', '').replace(' ', '').strip(), expected)
def test_get_operator_indices(): hostname = "https://pyxis.engineering.redhat.com/" data = [ { "path": "registry.io/index-image:4.5", "other": "stuff" }, { "path": "registry.io/index-image:4.6", "other2": "stuff2" }, ] ver = "4.5-4.6" org = "redhat" with requests_mock.Mocker() as m: m.get( "{0}v1/operators/indices?ocp_versions_range={1}&organization={2}". format(hostname, ver, org), json={"data": data}, ) my_client = pyxis_client.PyxisClient(hostname, 5, None, 3, True) res = my_client.get_operator_indices(ver, org) assert res == data
def test_dict_signing(self): in_dict = { "camliVersion": 1, "camliSigner": "sha1-aaaabbbbccccdddd", "someOtherData": "Hello" } out_str = (b'{\n\t"camliVersion": 1,\n' b'\t"camliSigner": "sha1-aaaabbbbccccdddd",\n' b'\t"someOtherData": "Hello"\n' b',"camliSig":"AAABBB"}') mock = requests_mock.Mocker() mock.post('https://example.com/perkeep/camli/sig/sign', content=out_str) with mock: result = self.signer.sign_dict(in_dict) posted_dict = parse_qs(mock.last_request.text) self.assertIn('json', posted_dict) self.assertDictEqual(json.loads(posted_dict['json'][0]), in_dict) self.assertEqual(out_str, result)
def test_send_delivery_status_to_service_succeeds_if_sent_at_is_none( notify_db_session, mocker): callback_api, template = _set_up_test_data('email', "delivery_status") datestr = datetime(2017, 6, 20) notification = create_notification(template=template, created_at=datestr, updated_at=datestr, sent_at=None, status='technical-failure') encrypted_data = _set_up_data_for_status_update(callback_api, notification) record_failure_mock = mocker.patch( 'app.celery.service_callback_tasks.record_failed_status_callback.apply_async' ) mocked = mocker.patch( 'app.celery.service_callback_tasks.send_delivery_status_to_service.retry' ) with requests_mock.Mocker() as request_mock: request_mock.post(callback_api.url, json={}, status_code=404) send_delivery_status_to_service(notification.id, encrypted_status_update=encrypted_data) record_failure_mock.assert_called() assert mocked.call_count == 0
async def test_wallbox_refresh_failed_invalid_auth(hass: HomeAssistant) -> None: """Test Wallbox setup with authentication error.""" await setup_integration(hass) assert entry.state == ConfigEntryState.LOADED with requests_mock.Mocker() as mock_request: mock_request.get( "https://user-api.wall-box.com/users/signin", json=authorisation_response, status_code=403, ) mock_request.put( "https://api.wall-box.com/v2/charger/12345", json=json.loads(json.dumps({CHARGER_MAX_CHARGING_CURRENT_KEY: 20})), status_code=403, ) wallbox = hass.data[DOMAIN][entry.entry_id] await wallbox.async_refresh() assert await hass.config_entries.async_unload(entry.entry_id) assert entry.state == ConfigEntryState.NOT_LOADED
def test_images_patch_error(proxy_server, signed_ticket): auth.add_signed_ticket(signed_ticket.data) response_code = 403 response_body = b"daemon response" response_headers = {"Content-Type": "text/plain"} with requests_mock.Mocker() as m: # Don't check anything, match errors are useless. m.patch(requests_mock.ANY, status_code=response_code, text=response_body) # Send a request to the proxy. res = http.patch(proxy_server, "/images/" + signed_ticket.id, { "op": "zero", "size": 1024 }) # Validate response to proxy client. assert res.status == response_code # Note: requests adds charset=UTF-8 on RHEL 7. assert response_headers["Content-Type"] in res.getheader("Content-Type") error = res.read() assert response_body in error
async def test_wallbox_refresh_failed_connection_error(hass: HomeAssistant) -> None: """Test Wallbox setup with connection error.""" await setup_integration(hass) assert entry.state == ConfigEntryState.LOADED with requests_mock.Mocker() as mock_request: mock_request.get( "https://user-api.wall-box.com/users/signin", json=authorisation_response, status_code=200, ) mock_request.get( "https://api.wall-box.com/chargers/status/12345", json=test_response, status_code=403, ) wallbox = hass.data[DOMAIN][entry.entry_id] await wallbox.async_refresh() assert await hass.config_entries.async_unload(entry.entry_id) assert entry.state == ConfigEntryState.NOT_LOADED
def test_images_options_old_daemon_without_options(proxy_server, signed_ticket): auth.add_signed_ticket(signed_ticket.data) path = "/images/" + signed_ticket.id # Note: the daemon does not allow OPTIONS. assumed_daemon_allow = {"OPTIONS", "GET", "PUT"} assumed_daemon_features = [] with requests_mock.Mocker() as m: m.options(requests_mock.ANY, status_code=405, content=b'{"detail": "Invalid method OPTIONS"}') res = http.request(proxy_server, "OPTIONS", path) # Validate the request. assert m.called assert m.last_request.path == path # Validate the response. assert res.status == 200 assert set(res.getheader("Allow").split(",")) == assumed_daemon_allow assert json.loads(res.read())["features"] == assumed_daemon_features
def test_write_points_from_dataframe(self): now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]], index=[now, now + timedelta(hours=1)], columns=["column_one", "column_two", "column_three"]) expected = ( b"foo column_one=\"1\",column_two=1i,column_three=1.0 0\n" b"foo column_one=\"2\",column_two=2i,column_three=2.0 " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo') self.assertEqual(m.last_request.body, expected) cli.write_points(dataframe, 'foo', tags=None) self.assertEqual(m.last_request.body, expected)
def subject(self, channel, hosts=None, disable=False): with requests_mock.Mocker() as mock: mock.register_uri(requests_mock.ANY, requests_mock.ANY, exc=requests_mock.exceptions.InvalidRequest) if hosts is None: mock.post("https://gql.twitch.tv/gql", json={}) else: mock.post("https://gql.twitch.tv/gql", response_list=[ {"json": {"data": {"user": { "id": host[0], "hosting": None if not host[1:4] else { "id": host[1], "login": host[2], "displayName": host[3] }}}} } for host in hosts ]) session = Streamlink() Twitch.bind(session, "tests.plugins.test_twitch") plugin = Twitch("https://twitch.tv/{0}".format(channel)) plugin.options.set("disable-hosting", disable) res = plugin._switch_to_hosted_channel() return res, plugin.channel, plugin._channel_id, plugin.author
def test_create_rol_without_identificatie(self, *mocks): url = get_operation_url("rol_create") zaak = ZaakFactory.create(zaaktype=ZAAKTYPE) zaak_url = get_operation_url("zaak_read", uuid=zaak.uuid) data = { "zaak": f"http://testserver{zaak_url}", "betrokkene": BETROKKENE, "betrokkene_type": RolTypes.natuurlijk_persoon, "roltype": ROLTYPE, "roltoelichting": "awerw", } with requests_mock.Mocker() as m: m.get(ROLTYPE, json=ROLTYPE_RESPONSE) with mock_client({ROLTYPE: ROLTYPE_RESPONSE}): response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(Rol.objects.count(), 1) self.assertEqual(NatuurlijkPersoon.objects.count(), 0) rol = Rol.objects.get() self.assertEqual(rol.betrokkene, BETROKKENE)
def test_get_transaction_result(self, _make_id): with requests_mock.Mocker() as m: expected_request = { 'id': 1234, 'jsonrpc': '2.0', 'method': 'icx_getTransactionResult', 'params': { 'txHash': self.transaction_hash } } response_json = { "jsonrpc": "2.0", "result": self.receipt, "id": 1234 } m.post(self.matcher, json=response_json) result_dict = self.icon_service.get_transaction_result(self.transaction_hash, full_response=True) actual_request = json.loads(m._adapter.last_request.text) result_content = result_dict['result'] self.assertEqual(expected_request, actual_request) self.assertEqual(result_success_v3.keys(), result_dict.keys()) self.assertTrue(is_transaction_result(result_content))
def test_it_is_exception(self, mock_get_logger, mock_run, patch_working_dir, patch_clone_dir): version = '0.44' dl_url = ('https://github.com/gohugoio/hugo/releases/download/v' f'{version}/hugo_{version}_Linux-64bit.tar.gz') create_file(patch_clone_dir / HUGO_VERSION, version) with pytest.raises(Exception): with requests_mock.Mocker() as m: m.get(dl_url, [ dict(exc=requests.exceptions.ConnectTimeout), dict(exc=requests.exceptions.ConnectTimeout), dict(exc=requests.exceptions.ConnectTimeout), dict(exc=requests.exceptions.ConnectTimeout), dict(exc=requests.exceptions.ConnectTimeout), ]) download_hugo() mock_get_logger.assert_called_once_with('download-hugo') mock_logger = mock_get_logger.return_value mock_logger.info.assert_has_calls([ call('.hugo-version found'), call(f'Using hugo version in .hugo-version: {version}'), call(f'Downloading hugo version {version}'), call(f'Failed attempt #1 to download hugo version: {version}'), call(f'Failed attempt #2 to download hugo version: {version}'), call(f'Failed attempt #3 to download hugo version: {version}'), call(f'Failed attempt #4 to download hugo version: {version}'), call(f'Failed attempt #5 to download hugo version: {version}'), ]) mock_run.assert_not_called()
def test_download_report_id(self): """Testing download with report id.""" report_out = StringIO() get_report_url = get_server_location() + \ REPORT_URI + '1' get_report_json_data = {'id': 1, 'report': [{'key': 'value'}]} test_dict = dict() test_dict[self.test_tar_filename] = get_report_json_data buffer_content = create_tar_buffer(test_dict) with requests_mock.Mocker() as mocker: mocker.get(get_report_url, status_code=200, headers={'X-Server-Version': VERSION}, content=buffer_content) nac = ReportDownloadCommand(SUBPARSER) args = Namespace(scan_job_id=None, report_id='1', path=self.test_tar_filename) with redirect_stdout(report_out): nac.main(args) self.assertEqual( report_out.getvalue().strip(), messages.DOWNLOAD_SUCCESSFULLY_WRITTEN % ('1', self.test_tar_filename))
def test_hosts_facts(self, mock_pool): """Test the hosts_facts method.""" scan_options = ScanOptions(max_concurrency=10) scan_options.save() scan_job, scan_task = create_scan_job( self.source, ScanTask.SCAN_TYPE_INSPECT, scan_name='test_62', scan_options=scan_options) scan_task.update_stats('TEST_SAT.', sys_scanned=0) api = SatelliteSixV2(scan_job, scan_task) hosts_url = 'https://{sat_host}:{port}/api/v2/hosts' with requests_mock.Mocker() as mocker: url = construct_url(url=hosts_url, sat_host='1.2.3.4') jsonresult = { 'total': 1, 'subtotal': 1, 'page': 1, 'per_page': 100, 'results': [{'id': 10, 'name': 'sys10'}] } # noqa mocker.get(url, status_code=200, json=jsonresult) api.hosts_facts() inspect_result = scan_task.inspection_result self.assertEqual(len(inspect_result.systems.all()), 1)