async def test_update_group_name(): with pook.use(): get_token_mock_1 = pook.post( 'https://foo.com/api/auth/v3/app_access_token/internal/', response_json={ 'code': 0, 'msg': 'OK', 'tenant_access_token': 'test-token' }) pook.get('https://foo.com/api/chat/v4/list', response_json={ 'code': 0, 'msg': 'OK', 'data': { 'groups': [{ 'chat_id': 'test_chat_id' }] } }) new_name = f'#名片审核 {datetime.now().isoformat()}' update_mock = pook.post('https://foo.com/api/chat/v4/update/', response_json={ 'code': 0, 'msg': 'OK', }) bot = FeishuBot('foo', 'bar', 'https://foo.com/api') groups = await bot.get_groups() g = groups[0] await bot.update_group_name(g['chat_id'], new_name) assert update_mock.calls == 1
async def test_upload_image(): image_url = 'https://img.xiaoduanshijian.com/f28cc520be6ee16e8141-c66f9f10-27bb-1.png' endpoint_url = 'https://foo.com/api/image/v4/put/' get_token_url = 'https://foo.com/api/auth/v3/app_access_token/internal/' with pook.use(): pook.get(image_url, response_body=b'abc') pook.post(get_token_url, response_json={ 'code': 0, 'msg': 'OK', 'tenant_access_token': 'test' }) pook.post(endpoint_url, response_json={ 'code': 0, 'msg': 'OK', 'data': { 'image_key': 'test-image-key' } }) bot = FeishuBot('foo', 'bar', 'https://foo.com/api') image_key = await bot.upload_image(image_url) assert image_key == 'test-image-key'
def test_search_on_github_cache_terraform_releases_200( tmp_working_dir, terraform_releases_html_after_v0_13_0, # noqa: F811 ): # noqa: D103 with mock.patch("io.BytesIO", AutoclosingBytesIO): with pook.use(): repo = "hashicorp/terraform" releases_url = "https://github.com/{}/releases?after=v0.13.0".format(repo) # A volatile mock that can only be invoked once pook.get( releases_url, reply=200, response_type="text/plain", response_body=terraform_releases_html_after_v0_13_0, response_headers={ "Status": "200 OK", "ETag": 'W/"df0474ebd25f223a95926ba58e11e77b"', "Cache-Control": "max-age=0, private, must-revalidate", "Date": formatdate(usegmt=True), }, times=1, ) patch_regex = r"[0-9]+(((-alpha|-beta|-rc)[0-9]+)|(?P<dev>-dev))?" patch = tfwrapper.search_on_github(repo, "0.12", patch_regex, "14") assert patch == "14" patch = tfwrapper.search_on_github(repo, "0.12", patch_regex, "") assert patch == "19" assert pook.isdone() assert not pook.pending_mocks() assert not pook.unmatched_requests()
def test_body_length(should): with pook.use(): pook.get('foo.com', reply=200, response_body='hello world') res = requests.get('http://foo.com') res | should.have.body.length(11) res | should.have.body.length.higher.than(10)
def test_status_ok(should): with pook.use(): pook.get('foo.com', reply=200) requests.get('http://foo.com') | should.be.ok with pytest.raises(AssertionError): pook.get('foo.com', reply=500) requests.get('http://foo.com') | should.be.ok
def test_status_error(should): with pook.use(): pook.get('foo.com', reply=500) requests.get('http://foo.com') | should.be.server_error with pytest.raises(AssertionError): pook.get('foo.com', reply=404) requests.get('http://foo.com') | should.be.server_error
def test_status_bad(should): with pook.use(): pook.get('foo.com', reply=403) requests.get('http://foo.com') | should.be.bad_request with pytest.raises(AssertionError): pook.get('foo.com', reply=204) requests.get('http://foo.com') | should.be.bad_request
def test_json_operator(should): with pook.use(): pook.get('foo.com', reply=200, response_json={'foo': 'bar'}) res = requests.get('http://foo.com') res | should.have.json.equal.to({'foo': 'bar'}) with pytest.raises(AssertionError): res | should.have.body('foo')
def test_body_operator(should): with pook.use(): pook.get('foo.com', reply=200, response_body='hello world') res = requests.get('http://foo.com') res | should.have.body.equal.to('hello world') with pytest.raises(AssertionError): res | should.have.body('foo')
async def test_refresh_token(): with pook.use(): # Populate token with request get_token_mock_1 = pook.post( 'https://foo.com/api/auth/v3/app_access_token/internal/', response_json={ 'code': 0, 'msg': 'OK', 'tenant_access_token': 'test' }) pook.get('https://foo.com/api/chat/v4/list').\ header('Authorization', 'Bearer test').\ reply(200).\ json({'code': 0, 'msg': 'OK', 'data': { 'groups': [ {'chat_id': 'chat_id_1', 'name': 'group_1'}, {'chat_id': 'chat_id_2', 'name': 'group_2'} ] }}) # Pass the first send text send_text_mock_1 = pook.post('https://foo.com/api/message/v4/send/', headers={'Authorization': 'Bearer test'}, response_json={ 'code': 0, 'msg': 'OK', 'data': {} }) # Fail the second send text with token expired send_text_mock_2 = pook.post('https://foo.com/api/message/v4/send/', headers={'Authorization': 'Bearer test'}, response_json={ 'code': 99991663, 'msg': 'token expired', }) # Feed the valid token get_token_mock_2 = pook.post( 'https://foo.com/api/auth/v3/app_access_token/internal/', response_json={ 'code': 0, 'msg': 'OK', 'tenant_access_token': 'test2' }) # System would try again send_text_mock_3 = pook.post('https://foo.com/api/message/v4/send/', headers={'Authorization': 'Bearer test2'}, response_json={ 'code': 0, 'msg': 'OK', 'data': {} }) bot = FeishuBot('foo', 'bar', 'https://foo.com/api') resp = await bot.send_text('hello world')
def test_header_presence(should): with pook.use(): pook.get('foo.com', reply=200, response_type='json') res = requests.get('http://foo.com') res | should.have.header('Content-Type') res | should.not_have.header('Server') with pytest.raises(AssertionError): res | should.have.header('Server')
def test_FUNC_call_WITH_responsive_url_EXPECT_call_successful() -> None: """ Check whether the call succeeded. :return: No return. """ with pook.use(): pook.get("https://example.com", status=200) status = HttpCall.call('GET', 'https://example.com').status assert status == 200
def test_FUNC_call_WITH_not_existing_url_EXPECT_not_reached() -> None: """ Check whether the call failed. :return: No return. """ with pook.use(): mock = pook.get("https://unreachable.com").error(HTTPError()).persist() with pytest.raises(NotReachedError): HttpCall.call('GET', 'https://unreachable.com')
def test_url_protocol_operator(should): with pook.use(): pook.get('foo.com', reply=200, persist=True, response_type='json') requests.get('http://foo.com') | should.have.url.protocol('http') # Strict comparison # requests.get('http://foo.com') | should.have.url('http://foo.com/') with pytest.raises(AssertionError): requests.get('http://foo.com') | should.have.url('bar')
def test_url_hostname_operator(should): with pook.use(): pook.get('foo.com', reply=200, persist=True, response_type='json') requests.get('http://foo.com') | should.have.url.hostname('foo.com') requests.get('http://foo.com') | should.have.url.hostname('foo', strict=False) with pytest.raises(AssertionError): requests.get('http://foo.com') | should.have.url('bar')
def test_body_match(should): with pook.use(): pook.get('foo.com', reply=200, response_body='hello world') res = requests.get('http://foo.com') res | should.have.body.to.match(r'(\w+) world$') res | should.have.body('hello world') pook.get('foo.com', reply=200, response_json={'foo': 'bar'}) res = requests.get('http://foo.com') res | should.have.body.json({'foo': 'bar'})
def test_FUNC_call_WITH_not_existing_endpoint_EXPECT_not_found() -> None: """ Check whether the call failed. :return: No return. """ with pook.use(): pook.get("https://example.com/does-not-exist", status=404) with pytest.raises(InternalError, match="Http call failed with status: 404."): HttpCall.call('GET', "https://example.com/does-not-exist")
def test_FUNC_call_WITH_network_failures_EXPECT_correct_number_of_retries( ) -> None: """ Check if the retry logic works correctly. :return: No return. """ with pook.use(): mock = pook.get("https://unreachable.com").error(HTTPError()).times(5) with pytest.raises(NotReachedError): HttpCall.call('GET', 'https://unreachable.com') assert mock.total_matches == 5
def test_url_path_operator(should): with pook.use(): pook.get('foo.com', reply=200, persist=True, response_type='json') pook.get('foo.com/bar/baz', reply=200, persist=True, response_type='json') requests.get('http://foo.com/') | should.have.url.path('/') res = requests.get('http://foo.com/bar/baz') res | should.have.url.path('/bar/baz') res | should.have.url.path('baz', strict=False)
def test_method_presence(should): with pook.use(): pook.get('foo.com', reply=200, response_type='json') res = requests.get('http://foo.com') res | should.have.method('GET') res | should.have.method.equal.to('get') res | should.have_not.method.equal.to('POST') with pytest.raises(AssertionError): res | should.have.method.equal.to('POST') with pytest.raises(AssertionError): res | should.have_not.method.equal.to('GET')
def test_search_on_github_cache_terraform_releases_does_not_cache_error_429( tmp_working_dir, terraform_releases_html_after_v0_13_0, # noqa: F811 ): # noqa: D103 with mock.patch("io.BytesIO", AutoclosingBytesIO): with pook.use(): repo = "hashicorp/terraform" releases_url = "https://github.com/{}/releases?after=v0.13.0".format( repo) # volatile mocks that can only be invoked once each pook.get( releases_url, reply=429, response_headers={ "Status": "429 Too Many Requests", "Date": formatdate(usegmt=True), "Retry-After": "120" }, times=1, ) pook.get( releases_url, reply=200, response_type="text/plain", response_body=terraform_releases_html_after_v0_13_0, response_headers={ "Status": "200 OK", "ETag": 'W/"df0474ebd25f223a95926ba58e11e77b"', "Cache-Control": "max-age=0, private, must-revalidate", "Date": formatdate(usegmt=True), }, times=1, ) patch_regex = r"[0-9]+(((-alpha|-beta|-rc)[0-9]+)|(?P<dev>-dev))?" # pook does not implement urllib3's retry logic so this first request will always return None during tests patch = tfwrapper.search_on_github(repo, "0.12", patch_regex, "14") assert patch is None patch = tfwrapper.search_on_github(repo, "0.12", patch_regex, "14") assert patch == "14" patch = tfwrapper.search_on_github(repo, "0.12", patch_regex, "") assert patch == "19" assert pook.isdone() assert not pook.pending_mocks() assert not pook.unmatched_requests()
def test_url_port_operator(should): with pook.use(): pook.get('foo.com', reply=200, persist=True, response_type='json') pook.get('https://foo.com', reply=200, persist=True, response_type='json') requests.get('http://foo.com') | should.have.url.port(80) requests.get('http://foo.com:8080') | should.have.url.port(8080) requests.get('https://foo.com') | should.have.url.port(443) with pytest.raises(AssertionError): requests.get('http://foo.com') | should.have.url('bar')
def test_FUNC_call_to_str_WITH_google_endpoint_EXPECT_successfull_call( ) -> None: """ Checks whether the http endpoint call to str sends request and receives a response. :return: No return. """ with pook.use(): pook.get('https://example.com') endpoint = HttpEndpoint( endpoint_url='https://example.com', method='GET', ) endpoint.call_to_str()
def test_FUNC_call_WITH_network_failures_EXPECT_correct_time_waiting() -> None: """ Check if the retry logic works correctly. :return: No return. """ with pook.use(): mock = pook.get("https://unreachable.com").error(HTTPError()).times(5) with pytest.raises(NotReachedError): start = time.time() HttpCall.call('GET', 'https://unreachable.com') end = time.time() time_taken = end - start # HttpCall uses an exponentiation algorithm that should result in about 8 seconds long total wait time. assert 7.5 < time_taken < 8.5
def test_header_value(should): with pook.use(): pook.get('foo.com', reply=200, response_type='json') res = requests.get('http://foo.com') res | should.have.header('Content-Type', 'application/json') (res | should.have.header('Content-Type') > should.be.equal('application/json')) with pytest.raises(AssertionError): res | should.have.header('Server', 'foo') with pytest.raises(AssertionError): res | should.have.header('Server')
def test_json_schema_operator(should): schema = { 'type': 'object', 'properties': { 'price': { 'type': 'number' }, 'name': { 'type': 'string' } } } with pook.use(): pook.get('foo.com').reply(200).json({'name': 'Eggs', 'price': 34.99}) res = requests.get('http://foo.com') res | should.satisfy.json_schema(schema)
def test_json_complex(should): json = { 'foo': { 'foo': 123, 'bar': [{ 'baz': True }] }, 'bar': [1, 2, 3], 'baz': { 'foo': False } } with pook.use(): pook.get('foo.com', reply=200, response_json=json) res = requests.get('http://foo.com') res | should.have.json.equal.to(json)
def test_json_chained_operators(should): json = { 'foo': { 'foo': 123, 'bar': [{ 'baz': True }] }, 'bar': [1, 2, 3], 'baz': { 'foo': False } } with pook.use(): pook.get('foo.com', reply=200, response_json=json) res = requests.get('http://foo.com') res | should.have.json.key('foo') > should.be.a('dict') res | should.have.json.key('foo').that.should.be.a('dict')
def test_json_schema_error(should): schema = { 'type': 'object', 'properties': { 'price': { 'type': 'number' }, 'name': { 'type': 'number' } } } with pook.use(): pook.get('foo.com').reply(200).json({'name': 'Eggs', 'price': True}) res = requests.get('http://foo.com') with pytest.raises(AssertionError): res | should.satisfy.json_schema(schema)
def test_url_operator(should): with pook.use(): pook.get('foo.com', reply=200, persist=True, response_type='json') requests.get('http://foo.com') | should.have.url('http://foo.com') res = requests.get('http://foo.com') res | should.have.url('foo.com') res | should.have.url.equal.to('http://foo.com') res | should.have.url.that.contains('foo.com') res | should.have.url.that.matches('foo.com/$') # Strict comparison res | should.have.url('http://foo.com/', strict=True) with pytest.raises(AssertionError): requests.get('http://foo.com') | should.have.url('bar') with pytest.raises(AssertionError): (requests.get('http://foo.com') | should.have.url('//foo.com', strict=True))