async def test_patch_global(client: lightkube.AsyncClient): req = respx.patch("https://localhost:9443/api/v1/nodes/xx").respond( json={'metadata': { 'name': 'xx' }}) pod = await client.patch(Node, "xx", [{ "op": "add", "path": "/metadata/labels/x", "value": "y" }], patch_type=types.PatchType.JSON) assert pod.metadata.name == 'xx' assert req.calls[0][0].headers[ 'Content-Type'] == "application/json-patch+json" # PatchType.APPLY + force req = respx.patch( "https://localhost:9443/api/v1/nodes/xy?fieldManager=test&force=true" ).respond(json={'metadata': { 'name': 'xy' }}) node = await client.patch(Node, "xy", Pod(metadata=ObjectMeta(labels={'l': 'ok'})), patch_type=types.PatchType.APPLY, field_manager='test', force=True) assert node.metadata.name == 'xy' assert req.calls[0][0].headers[ 'Content-Type'] == "application/apply-patch+yaml" await client.close()
def test_patch_namespaced(client: lightkube.Client): # Default PatchType.STRATEGIC req = respx.patch("https://localhost:9443/api/v1/namespaces/default/pods/xx").respond(json={'metadata': {'name': 'xx'}}) pod = client.patch(Pod, "xx", Pod(metadata=ObjectMeta(labels={'l': 'ok'}))) assert pod.metadata.name == 'xx' assert req.calls[0][0].headers['Content-Type'] == "application/strategic-merge-patch+json" # PatchType.MERGE req = respx.patch("https://localhost:9443/api/v1/namespaces/other/pods/xx").respond(json={'metadata': {'name': 'xx'}}) pod = client.patch(Pod, "xx", Pod(metadata=ObjectMeta(labels={'l': 'ok'})), namespace='other', patch_type=types.PatchType.MERGE, force=True) assert pod.metadata.name == 'xx' assert req.calls[0][0].headers['Content-Type'] == "application/merge-patch+json" assert 'force' not in str(req.calls[0][0].url) # force is ignored for non APPLY patch types # PatchType.APPLY req = respx.patch("https://localhost:9443/api/v1/namespaces/other/pods/xy?fieldManager=test").respond( json={'metadata': {'name': 'xy'}}) pod = client.patch(Pod, "xy", Pod(metadata=ObjectMeta(labels={'l': 'ok'})), namespace='other', patch_type=types.PatchType.APPLY, field_manager='test') assert pod.metadata.name == 'xy' assert req.calls[0][0].headers['Content-Type'] == "application/apply-patch+yaml" # PatchType.APPLY + force req = respx.patch("https://localhost:9443/api/v1/namespaces/other/pods/xz?fieldManager=test&force=true").respond( json={'metadata': {'name': 'xz'}}) pod = client.patch(Pod, "xz", Pod(metadata=ObjectMeta(labels={'l': 'ok'})), namespace='other', patch_type=types.PatchType.APPLY, field_manager='test', force=True) assert pod.metadata.name == 'xz' assert req.calls[0][0].headers['Content-Type'] == "application/apply-patch+yaml" # PatchType.APPLY without field_manager with pytest.raises(ValueError, match="field_manager"): client.patch(Pod, "xz", Pod(metadata=ObjectMeta(labels={'l': 'ok'})), namespace='other', patch_type=types.PatchType.APPLY)
async def test_apply_global(client: lightkube.AsyncClient): req = respx.patch( "https://localhost:9443/api/v1/nodes/xy?fieldManager=test").respond( json={'metadata': { 'name': 'xy' }}) node = await client.apply(Node(metadata=ObjectMeta(name='xy')), field_manager='test') assert node.metadata.name == 'xy' assert req.calls[0][0].headers[ 'Content-Type'] == "application/apply-patch+yaml" # sub-resource + force req = respx.patch( "https://localhost:9443/api/v1/nodes/xx/status?fieldManager=a&force=true" ).respond(json={'metadata': { 'name': 'xx' }}) node = await client.apply(Node.Status(), name='xx', field_manager='a', force=True) assert node.metadata.name == 'xx' assert req.calls[0][0].headers[ 'Content-Type'] == "application/apply-patch+yaml" await client.close()
async def test_http_methods(client): async with respx.mock: url = "https://foo.bar" route = respx.get(url, path="/") % 404 respx.post(url, path="/").respond(200) respx.post(url, path="/").respond(201) respx.put(url, path="/").respond(202) respx.patch(url, path="/").respond(500) respx.delete(url, path="/").respond(204) respx.head(url, path="/").respond(405) respx.options(url, path="/").respond(status_code=501) respx.request("GET", url, path="/baz/").respond(status_code=204) url += "/" response = httpx.get(url) assert response.status_code == 404 response = await client.get(url) assert response.status_code == 404 response = httpx.get(url + "baz/") assert response.status_code == 204 response = await client.get(url + "baz/") assert response.status_code == 204 response = httpx.post(url) assert response.status_code == 201 response = await client.post(url) assert response.status_code == 201 response = httpx.put(url) assert response.status_code == 202 response = await client.put(url) assert response.status_code == 202 response = httpx.patch(url) assert response.status_code == 500 response = await client.patch(url) assert response.status_code == 500 response = httpx.delete(url) assert response.status_code == 204 response = await client.delete(url) assert response.status_code == 204 response = httpx.head(url) assert response.status_code == 405 response = await client.head(url) assert response.status_code == 405 response = httpx.options(url) assert response.status_code == 501 response = await client.options(url) assert response.status_code == 501 assert route.called is True assert respx.calls.call_count == 8 * 2
async def test_mock_edit_followup_message_fail_async( followup_object_with_already_set_id: FollowUpMessages, create_example_response): respx.patch( f"https://discord.com/api/v8/webhooks/APPID/exampleToken/messages/SampleMessageId" ).mock(return_value=Response(404, json={"id": "exampleIncomingToken"})) with pytest.raises(DiscordAPIError): await followup_object_with_already_set_id.async_edit_follow_up_message( updated_message=create_example_response)
def test_single_edit_command_globally(dispike_object: Dispike, example_edit_command: DiscordCommand): respx.patch("https://discord.com/api/v8/applications/APPID/commands").mock( return_value=Response( 200, json=example_edit_command.dict(), )) _edit_command = dispike_object.edit_command( new_command=example_edit_command) assert isinstance(_edit_command, DiscordCommand) == True, type(_edit_command) assert _edit_command.id == example_edit_command.id assert _edit_command.name == example_edit_command.name
def test_mock_edit_followup_message_sync( followup_object_with_already_set_id: FollowUpMessages, create_example_response): respx.patch( f"https://discord.com/api/v8/webhooks/APPID/exampleToken/messages/SampleMessageId" ).mock(return_value=Response(200, json={"id": "exampleIncomingToken"})) assert (followup_object_with_already_set_id.edit_follow_up_message( updated_message=create_example_response) == True) with pytest.raises(TypeError): followup_object_with_already_set_id._message_id = None followup_object_with_already_set_id.edit_follow_up_message( updated_message=create_example_response)
async def test_http_methods(client): async with respx.mock: url = "https://foo.bar/" m = respx.get(url, status_code=404) respx.post(url, status_code=201) respx.put(url, status_code=202) respx.patch(url, status_code=500) respx.delete(url, status_code=204) respx.head(url, status_code=405) respx.options(url, status_code=501) response = httpx.get(url) assert response.status_code == 404 response = await client.get(url) assert response.status_code == 404 response = httpx.post(url) assert response.status_code == 201 response = await client.post(url) assert response.status_code == 201 response = httpx.put(url) assert response.status_code == 202 response = await client.put(url) assert response.status_code == 202 response = httpx.patch(url) assert response.status_code == 500 response = await client.patch(url) assert response.status_code == 500 response = httpx.delete(url) assert response.status_code == 204 response = await client.delete(url) assert response.status_code == 204 response = httpx.head(url) assert response.status_code == 405 response = await client.head(url) assert response.status_code == 405 response = httpx.options(url) assert response.status_code == 501 response = await client.options(url) assert response.status_code == 501 assert m.called is True assert respx.stats.call_count == 7 * 2
def test_bulk_edit_command_globally(dispike_object: Dispike, example_edit_command: DiscordCommand): respx.patch("https://discord.com/api/v8/applications/APPID/commands").mock( return_value=Response( 200, json=[example_edit_command.dict(), example_edit_command.dict()], )) _edit_command = dispike_object.edit_command( new_command=example_edit_command, bulk=True) assert isinstance(_edit_command, list) == True assert len(_edit_command) == 2 for command in _edit_command: assert isinstance(command, DiscordCommand) assert command.id == example_edit_command.id assert command.name == example_edit_command.name
def test_failed_single_edit_command_guild_only( dispike_object: Dispike, example_edit_command: DiscordCommand): respx.patch( "https://discord.com/api/v8/applications/APPID/guilds/EXAMPLE_GUILD/commands/1234" ).mock(return_value=Response( 401, json=example_edit_command.dict(), )) _edit_command = dispike_object.edit_command( new_command=example_edit_command, command_id=1234, guild_only=True, guild_id_passed="EXAMPLE_GUILD", ) assert _edit_command == False
def test_field_manager(kubeconfig): config = KubeConfig.from_file(str(kubeconfig)) client = lightkube.Client(config=config, field_manager='lightkube') respx.patch("https://localhost:9443/api/v1/nodes/xx?fieldManager=lightkube").respond(json={'metadata': {'name': 'xx'}}) client.patch(Node, "xx", [{"op": "add", "path": "/metadata/labels/x", "value": "y"}], patch_type=types.PatchType.JSON) respx.post("https://localhost:9443/api/v1/namespaces/default/pods?fieldManager=lightkube").respond(json={'metadata': {'name': 'xx'}}) client.create(Pod(metadata=ObjectMeta(name="xx", labels={'l': 'ok'}))) respx.put("https://localhost:9443/api/v1/namespaces/default/pods/xy?fieldManager=lightkube").respond( json={'metadata': {'name': 'xy'}}) client.replace(Pod(metadata=ObjectMeta(name="xy"))) respx.put("https://localhost:9443/api/v1/namespaces/default/pods/xy?fieldManager=override").respond( json={'metadata': {'name': 'xy'}}) client.replace(Pod(metadata=ObjectMeta(name="xy")), field_manager='override')
async def test_send_defer_message_failed(dispike_object: Dispike, ): route = respx.patch( "https://discord.com/api/v8/webhooks/APPID/FAKETOKEN/messages/@original", ).mock(return_value=Response(500, ), ) _sample_interaction = IncomingDiscordSlashInteraction( **{ "channel_id": "123123", "data": { "id": "12312312", "name": "sample", "options": [{ "name": "message", "value": "test" }], }, "guild_id": "123123", "id": "123123123132", "member": { "deaf": False, "is_pending": False, "joined_at": "2019-05-12T18:36:16.878000+00:00", "mute": False, "nick": None, "pending": False, "permissions": "2147483647", "premium_since": None, "roles": [ "123123", "123123", "1231233", "1231233133", "12412412414", ], "user": { "avatar": "b723979992a56", "discriminator": "3333", "id": "234234213122123", "public_flags": 768, "username": "******", }, }, "token": "FAKETOKEN", "type": 2, "version": 1, }) with pytest.raises(httpx.HTTPError): await dispike_object.send_deferred_message( original_context=_sample_interaction, new_message=DiscordResponse(content="working"), )
def test_apply_namespaced(client: lightkube.Client): req = respx.patch("https://localhost:9443/api/v1/namespaces/default/pods/xy?fieldManager=test").respond( json={'metadata': {'name': 'xy'}}) pod = client.apply(Pod(metadata=ObjectMeta(name='xy')), field_manager='test') assert pod.metadata.name == 'xy' assert req.calls[0][0].headers['Content-Type'] == "application/apply-patch+yaml" # custom namespace, force req = respx.patch("https://localhost:9443/api/v1/namespaces/other/pods/xz?fieldManager=a&force=true").respond( json={'metadata': {'name': 'xz'}}) pod = client.apply(Pod(metadata=ObjectMeta(name='xz', namespace='other')), field_manager='a', force=True) assert pod.metadata.name == 'xz' assert req.calls[0][0].headers['Content-Type'] == "application/apply-patch+yaml" # sub-resource req = respx.patch("https://localhost:9443/api/v1/namespaces/default/pods/xx/status?fieldManager=a").respond( json={'metadata': {'name': 'xx'}}) pod = client.apply(Pod.Status(), name='xx', field_manager='a') assert pod.metadata.name == 'xx' assert req.calls[0][0].headers['Content-Type'] == "application/apply-patch+yaml"
async def test_async_update_failed(async_client): request = respx.patch(f"{API_BASE_URL}/v1/notifications/1/", status_code=404) response = await async_client.notifications.update( id=1, name="new_name", http_method=HttpMethod.GET, destination_url="url", ) assert request.called assert response.status_code == 404
async def test_async_update_200(async_client): request = respx.patch( f"{API_BASE_URL}/v1/groups/persons/1/", status_code=200, content={ "id": 1, "name": "new_name" }, ) response = await async_client.groups.update(1, name="new_name") assert request.called assert response.status_code == 200 assert response.json()["name"] == "new_name"
async def test_async_update_ok(async_client): request = respx.patch( f"{IAM_BASE_URL}/v1/spaces/1/", status_code=200, content={ "id": 1, "name": "new_name" }, ) response = await async_client.spaces.update(id=1, name="new_name") assert request.called assert response.status_code == 200 assert response.json()["name"] == "new_name"
def test_token_update_by_id_deactivate_200(client): request = respx.patch( f"{IAM_BASE_URL}/v1/tokens/1/", status_code=200, content={ "key": "token", "is_active": False }, ) tokens = client.tokens.update(token_id_or_key=1, is_active=False) assert request.called assert tokens.status_code == 200 assert tokens.json()["key"] == "token" assert tokens.json()["is_active"] is False
async def test_async_update_by_key_200(async_client): request = respx.patch( f"{IAM_BASE_URL}/v1/tokens/token/", status_code=200, content={ "key": "token", "is_active": True }, ) tokens = await async_client.tokens.update(token_id_or_key="token", is_active=True) assert request.called assert tokens.status_code == 200 assert tokens.json()["key"] == "token" assert tokens.json()["is_active"]
async def test_async_update_200(async_client): request = respx.patch( f"{API_BASE_URL}/v1/settings/thresholds/", status_code=200, content={ "exact": 2, "ha": 2, "junk": 2 }, ) response = await async_client.settings.update(2, 2, 2) assert request.called assert response.status_code == 200 assert response.json() == {"exact": 2, "ha": 2, "junk": 2}
async def test_async_update_ok(async_client): request = respx.patch( f"{API_BASE_URL}/v1/notifications/1/", status_code=200, content={ "name": "new_name", "id": 1 }, ) response = await async_client.notifications.update( id=1, name="new_name", http_method=HttpMethod.GET, destination_url="url", ) assert request.called assert response.status_code == 200 assert response.json()["name"] == "new_name"
async def test_async_update_200(async_client): request = respx.patch( f"{API_BASE_URL}/v1/sources/1/", status_code=200, content={ "id": 1, "name": "source_name" }, ) response = await async_client.sources.update( id=1, name="source_name", license_type=SourceLicense.ADVANCED) request_content = request.calls[0][0] request_content.read() assert request.called assert json.loads(request_content.content) == json.loads( b'{"name": "source_name", "license_type": "advanced"}') assert response.status_code == 200 assert response.json()["name"] == "source_name"