def test_last_success_build_info_handles_no_result( drone: Drone, requests_mock: Mocker) -> None: """ Given: A drone pipeline with no successful builds. When: last_success_build_info is called. Then: DroneBuildError exception is raised. """ requests_mock.get( f"{drone.drone_url}/api/repos/owner/repository/builds", json=[ { "id": 882, "number": 209, "finished": 1, "status": "failure", "source": "feat/1", "target": "feat/1", }, ], ) with pytest.raises(DroneBuildError) as error: drone.last_success_build_info("owner/repository") assert "There are no successful jobs with target branch master" in str( error.value)
def test_build_info_returns_expected_json(drone: Drone, requests_mock: Mocker) -> None: """ Given: A Drone adapter object. When: The build_info method is called for id 274. Then: The json of the 274 build is returned. """ response_json = { "id": 879, "status": "success", "number": "209", "trigger": "trigger_author", "event": "promote", "message": "commit message", "source": "master", "after": "9d924b358sflwegk30bbfa0571f754ec2a0b7457", "target": "master", "author_name": "Commit Author", "deploy_to": "production", "started": 1591128214, "finished": 0, "stages": [], } requests_mock.get( f"{drone.drone_url}/api/repos/owner/repository/builds/274", json=response_json, status_code=200, ) result = drone.build_info("owner/repository", 274) assert result == response_json
def test_github_device_flow(requests_mock: RequestsMocker, monkeypatch: MonkeyPatch) -> None: device_code = '111' user_code = '123-456' verification_uri = 'https://github.com' expires_in = 900 interval = 1 access_token = 'aaa-ccc' requests_mock.post('https://github.com/login/device/code', text=urlencode({ 'device_code': device_code, 'user_code': user_code, 'verification_uri': verification_uri, 'expires_in': expires_in, 'interval': interval })) requests_mock.post('https://github.com/login/oauth/access_token', text=urlencode({ 'access_token': access_token, })) def noop(s: float) -> None: pass monkeypatch.setattr(time, "sleep", noop) def write_token(access_token: AccessToken) -> None: assert access_token with github_device_flow(write_token) as verif_codes: assert verif_codes
def test_notes_api_get_all_notes_etag_cache(example_note_gen: Iterator[Note], notes_api: NotesApi, requests_mock: RequestsMocker): example_note_list = list(example_note_gen) requests_mock.get( f'https://{notes_api.hostname}/index.php/apps/notes/api/v1/notes', json=[note.to_dict() for note in example_note_list], headers={'ETag': 'some hash'}, ) notes = notes_api.get_all_notes() assert list(notes) == example_note_list # This time it should return the cached notes with RequestsMocker() as cache_requests_mock: cache_requests_mock.get( f'https://{notes_api.hostname}/index.php/apps/notes/api/v1/notes', request_headers={'If-None-Match': 'some hash'}, status_code=304, ) notes = notes_api.get_all_notes() assert list(notes) == example_note_list
def test_get_wrong_recipes(requests_mock: Mocker, recipes_client): requests_mock.get(RECIPE_CONFIG.RECIPE_SERVER + '/api/v1/recipes', json={'recipes': ['1']}) requests_mock.get(RECIPE_CONFIG.RECIPE_SERVER + '/api/v1/recipes/r/1', text='Not Found', status_code=404) result = recipes_client.get_full_recipes() assert [] == result
def test_notes_api_get_single_note(example_note: Note, notes_api: NotesApi, requests_mock: RequestsMocker): requests_mock.get( f'https://{notes_api.hostname}/index.php/apps/notes/api/v1/notes/1337', json=example_note.to_dict(), ) assert notes_api.get_single_note(1337) == example_note
def test_get_all_cves(requests_mock: Mocker, tmpdir): # todo: this is a placeholder test that currently is expected to fail. all_cves_response = get_test_file("all_cves.json") requests_mock.get("https://services.nvd.nist.gov/rest/json/cves/1.0", text=all_cves_response) result = get_all_cves() assert requests_mock.called
def test_get_all_recipes(requests_mock: Mocker, recipes_client): requests_mock.get(RECIPE_CONFIG.RECIPE_SERVER + '/api/v1/recipes', json={'recipes': ['1']}) requests_mock.get(RECIPE_CONFIG.RECIPE_SERVER + '/api/v1/recipes/r/1', json={ 'id': 1, 'components': [] }) result = recipes_client.get_full_recipes() assert [{'id': 1, 'components': []}] == result
def test_promote_launches_promote_drone_job(drone: Drone, requests_mock: Mocker, caplog: LogCaptureFixture) -> None: """ Given: A Drone adapter. When: Using the promote method. Then: Calls the promote API method with the desired build number. """ requests_mock.get( f"{drone.drone_url}/api/repos/owner/repository/builds/172", json={ "id": 882, "number": 172, "status": "success", "after": "9fc1ad6ebf12462f3f9773003e26b4c6f54a772e", "target": "master", "event": "push", "message": "updated README", }, ) promote_url = ( f"{drone.drone_url}/api/repos/owner/repository/builds/172/promote" "?target=production") requests_mock.post( promote_url, json={ "id": 100207, "number": 174, "parent": 172, "status": "pending", "event": "promote", "message": "updated README", "before": "e3320539a4c03ccfda992641646deb67d8bf98f3", "after": "9fc1ad6ebf12462f3f9773003e26b4c6f54a772e", "source": "master", "target": "master", "author_login": "******", "author_name": "The Octocat", "sender": "bradrydzewski", "started": 0, "finished": 0, "stages": [], }, ) result = drone.promote("owner/repository", 172, "production") assert result == 174 assert requests_mock.request_history[-1].method == "POST" assert requests_mock.request_history[-1].url == promote_url assert ( "drode.adapters.drone", logging.INFO, "Job #174 has started.", ) in caplog.record_tuples
def test_get_cve_by_id(requests_mock: Mocker): cve_id = "CVE-2021-3165" cve_data = get_test_file(f"{cve_id}.json") requests_mock.get( f"https://services.nvd.nist.gov/rest/json/cve/1.0/{cve_id}", text=cve_data) result = get_cve_by_id(cve_id) assert requests_mock.called_once assert "*****@*****.**" in result
def test_check_config_happy_path(drone: Drone, caplog: LogCaptureFixture, requests_mock: Mocker) -> None: """ Given: A correctly configured Drone adapter object. When: Configuration is checked Then: The user is informed of the correct state. """ requests_mock.get(f"{drone.drone_url}/api/user/repos", text="OK") drone.check_configuration() # act assert ("drode.adapters.drone", logging.INFO, "Drone: OK") in caplog.record_tuples
def test_notes_api_get_all_notes_response_status_exceptions( status_code: int, expectation: ContextManager, notes_api: NotesApi, requests_mock: RequestsMocker, ): requests_mock.get( f'https://{notes_api.hostname}/index.php/apps/notes/api/v1/notes', status_code=status_code, ) with expectation: notes_api.get_all_notes()
def test_notes_api_update_note(example_note: Note, notes_api: NotesApi, requests_mock: RequestsMocker): example_note.id = 1337 # Server updates this server_note = example_note server_note.update_modified() requests_mock.put( f'https://{notes_api.hostname}/index.php/apps/notes/api/v1/notes/{example_note.id}', # noqa: E501 json=server_note.to_dict(), ) assert notes_api.update_note(example_note) == server_note
def test_notes_api_get_all_notes( example_note_gen: Iterator[Note], notes_api_no_etag_caching: NotesApi, requests_mock: RequestsMocker, ): example_note_list = list(example_note_gen) requests_mock.get( f'https://{notes_api_no_etag_caching.hostname}/index.php/apps/notes/api/v1/notes', # noqa: E501 json=[note.to_dict() for note in example_note_list], ) notes = notes_api_no_etag_caching.get_all_notes() assert list(notes) == example_note_list
def test_notes_api_update_note_id_not_set(example_note: Note, notes_api: NotesApi, requests_mock: RequestsMocker): example_note.id = None # Server updates this server_note = example_note server_note.update_modified() requests_mock.put( f'https://{notes_api.hostname}/index.php/apps/notes/api/v1/notes/{example_note.id}', # noqa: E501 json=server_note.to_dict(), ) with pytest.raises(ValueError): assert notes_api.update_note(example_note) == server_note
def test_notes_api_create_note(example_note: Note, notes_api: NotesApi, requests_mock: RequestsMocker): # Server sets this example_note.id = None example_note.modified = None server_note = example_note server_note.id = 1337 server_note.update_modified() requests_mock.post( f'https://{notes_api.hostname}/index.php/apps/notes/api/v1/notes', json=server_note.to_dict(), ) assert notes_api.create_note(example_note) == server_note
def test_get_generates_post_request(drone: Drone, requests_mock: Mocker) -> None: """ Given: A Drone adapter When: Using the get method with the post argument Then: a requests object is returned with the query result. """ requests_mock.post("http://url", text="hi") result = drone.get("http://url", "post") assert result.text == "hi" assert requests_mock.request_history[0].method == "POST" assert (requests_mock.request_history[0].headers["Authorization"] == "Bearer drone_token")
def test_check_config_unauthorized_error(drone: Drone, caplog: LogCaptureFixture, requests_mock: Mocker) -> None: """ Given: An incorrectly configured Drone adapter object. When: Configuration is checked. Then: The user is informed of the incorrect state and an exception is raised. """ requests_mock.get(f"{drone.drone_url}/api/user/repos", status_code=401) with pytest.raises(DroneConfigurationError): drone.check_configuration() assert ("drode.adapters.drone", logging.ERROR, "Drone: KO") in caplog.record_tuples
def test_notes_api_update_note_response_status_exceptions( status_code: int, expectation: ContextManager, example_note: Note, notes_api: NotesApi, requests_mock: RequestsMocker, ): example_note.id = 1337 requests_mock.put( f'https://{notes_api.hostname}/index.php/apps/notes/api/v1/notes/{example_note.id}', # noqa: E501 status_code=status_code, ) with expectation: notes_api.update_note(example_note)
def test_search_unavailable(self): address_validation = PDOKAddressValidation() with Mocker() as m: m.get(address_validation.address_validation_url, status_code=400) self.assertRaises(AddressValidationUnavailableException, address_validation._search, self.address_dict)
def test_search_atlas_with_connection_error(self): address_validation = AddressValidation() with Mocker() as m: m.get(self._get_atlas_search_url(), exc=ConnectionError) self.assertRaises(AddressValidationUnavailableException, address_validation._search, self.address_dict)
def test_search_atlas_with_unsuccessful_http_code(self): address_validation = AddressValidation() with Mocker() as m: m.get(self._get_atlas_search_url(), status_code=400) self.assertRaises(AddressValidationUnavailableException, address_validation._search, self.address_dict)
def empty_page(): page = { "data": [], "meta": { "record_count": 0 }, "links": { "first": "first", "last": "last" }, } with Mocker() as mocker: params = { "include": "related", "fields[tests]": "field,related", "page[size]": 10, "page[number]": 1, } mocker.register_uri( "GET", f"http://test/api/tests/?{urlencode(params)}", status_code=200, json=page, ) yield mocker
def test_jsonapi_manager_iterator_with_included(): cache.clear() page = { "data": [ { "id": "137", "type": "tests", "attributes": {} }, ], "included": [{ "id": "42", "type": "tests", "attributes": { "field": "Included Record", }, }], } with Mocker() as mocker: params = { "include": "related", "fields[tests]": "field,related", "page[size]": 10, "page[number]": 1, } mocker.register_uri( "GET", f"http://test/api/tests/?{urlencode(params)}", status_code=200, json=page, ) manager = JSONAPIManager(Dummy) list(manager.iterator()) assert cache.get("jsonapi:tests:42").field == "Included Record"
def test_build_info_raises_exception_if_build_number_doesnt_exist( drone: Drone, requests_mock: Mocker) -> None: """ Given: A Drone adapter object. When: The build_info method is called with an inexistent job id. Then: A DroneAPIError exception is raised """ requests_mock.get( f"{drone.drone_url}/api/repos/owner/repository/builds/9999", status_code=404, ) with pytest.raises(DroneBuildError) as error: drone.build_info("owner/repository", 9999) assert "The build 9999 was not found at the pipeline owner/repository" in str( error.value)
def test_search_atlas_successful_request(self): address_validation = AddressValidation() search_result = self._get_atlas_response() expected = search_result["results"] with Mocker() as m: m.get(self._get_atlas_search_url(), text=dumps(search_result)) self.assertEqual(address_validation._search(self.address_dict), expected)
def test_last_build_info_returns_the_last_build_json( drone: Drone, requests_mock: Mocker) -> None: """ Given: A pipeline with multiple build jobs. When: The last_build_info is called. Then: The last job build information is returned. """ response_json = [ { "id": 882, "number": 209, "finished": 1, "status": "success", "source": "feat/1", "target": "feat/1", }, { "id": 881, "number": 208, "finished": 1, "status": "success", "source": "master", "target": "master", "event": "promote", }, { "id": 880, "number": 207, "finished": 1, "status": "success", "source": "master", "target": "master", "event": "push", }, ] requests_mock.get( f"{drone.drone_url}/api/repos/owner/repository/builds", json=response_json, ) result = drone.last_build_info("owner/repository") assert result == response_json[0]
def test_notes_api_get_api_version_requests_mock( notes_api: NotesApi, requests_mock: RequestsMocker): requests_mock.get( f'https://{notes_api.hostname}/ocs/v2.php/cloud/capabilities', json={ 'ocs': { 'data': { 'capabilities': { 'notes': { 'api_version': ['0.2', '1.0'], 'version': '3.6.0' } } } } }, ) assert '1.0' == notes_api.get_api_version()
def test_last_success_build_info_searches_master_and_push_events_by_default( drone: Drone, requests_mock: Mocker) -> None: """ Given: A Drone adapter object. When: The last_success_build_info is called. Then: The last successful push event to master build number is returned. """ requests_mock.get( f"{drone.drone_url}/api/repos/owner/repository/builds", json=[ { "id": 882, "number": 209, "finished": 1, "status": "success", "source": "feat/1", "target": "feat/1", }, { "id": 881, "number": 208, "finished": 1, "status": "success", "source": "master", "target": "master", "event": "promote", }, { "id": 880, "number": 207, "finished": 1, "status": "success", "source": "master", "target": "master", "event": "push", }, ], ) result = drone.last_success_build_info("owner/repository")["number"] assert result == 207
def test_search_successful_request(self): address_validation = PDOKAddressValidation() result = self._get_mocked_response() expected = result["response"]["docs"] with Mocker() as m: m.get(address_validation.address_validation_url, text=dumps(result)) self.assertEqual(address_validation._search(self.address_dict), expected)