Best Python code snippet using testcontainers-python_python
main_tests.py
Source:main_tests.py
...3import json4from testcontainers.compose import DockerCompose5def test_can_spawn_service_datastore_via_compose():6 with DockerCompose('.') as compose:7 host = compose.get_service_host("datastore", 8081)8 port = compose.get_service_port("datastore", 8081)9 assert host == "0.0.0.0"10 assert port == "8081"11def test_can_spawn_service_app_via_compose():12 with DockerCompose('.') as compose:13 host = compose.get_service_host("app", 8080)14 port = compose.get_service_port("app", 8080)15 assert host == "0.0.0.0"16 assert port == "8080"17def test_can_add_and_retrieve_correct_birthdate():18 with DockerCompose('.') as compose:19 compose.get_service_host("datastore", 8081)20 compose.get_service_port("datastore", 8081)21 app_host = compose.get_service_host("app", 8080)22 app_port = compose.get_service_port("app", 8080)23 # Test a correct formated date in the past can be added24 payload = '{\"dateOfBirth\": \"1988-1-14\"}'25 headers = {'Content-type': 'application/json'}26 r = requests.put("http://{}:{}/hello/daniel".format(app_host,app_port), headers=headers, data=payload)27 assert r.status_code == 20428 assert r.content == b''29 # Test the previous inserted birthdate can be retrieved30 r = requests.get("http://{}:{}/hello/daniel".format(app_host,app_port))31 assert r.status_code == 20032 assert 'Hello, daniel! Your birthday is in' in str(r.content)33 # Insert a birthdate which is today and retrieve the gratulations message34 today = datetime.datetime.today()35 birth_date = datetime.datetime(2000,today.month,today.day)36 payload = json.dumps({37 "dateOfBirth": birth_date.strftime('%Y-%m-%d')38 })39 headers = {'Content-type': 'application/json'}40 r = requests.put("http://{}:{}/hello/john".format(app_host,app_port), headers=headers, data=payload)41 r = requests.get("http://{}:{}/hello/john".format(app_host,app_port))42 assert r.status_code == 20043 assert 'Hello, john! Happy birthday!' in str(r.content)44def test_fail_when_adding_a_birthdate_in_the_future():45 with DockerCompose('.') as compose:46 compose.get_service_host("datastore", 8081)47 compose.get_service_port("datastore", 8081)48 app_host = compose.get_service_host("app", 8080)49 app_port = compose.get_service_port("app", 8080)50 tomorrow = datetime.datetime.today() + datetime.timedelta(days=1)51 payload = json.dumps({52 "dateOfBirth": tomorrow.strftime('%Y-%m-%d')53 })54 headers = {'Content-type': 'application/json'}55 r = requests.put("http://{}:{}/hello/daniel".format(app_host,app_port), headers=headers, data=payload)56 57 assert 'cannot be in the future' in str(r.content)58 assert r.status_code == 400 59def test_fails_when_using_wrong_date_format():60 with DockerCompose('.') as compose:61 compose.get_service_host("datastore", 8081)62 compose.get_service_port("datastore", 8081)63 app_host = compose.get_service_host("app", 8080)64 app_port = compose.get_service_port("app", 8080)65 payload = json.dumps({66 "dateOfBirth": "14-01-1988"67 })68 headers = {'Content-type': 'application/json'}69 r = requests.put("http://{}:{}/hello/daniel".format(app_host,app_port), headers=headers, data=payload)70 assert 'dateOfBirth is missing or format is not' in str(r.content)71 assert r.status_code == 40572def test_fails_when_username_has_numbers():73 with DockerCompose('.') as compose:74 app_host = compose.get_service_host("app", 8080)75 app_port = compose.get_service_port("app", 8080)76 r = requests.get("http://{}:{}/hello/d4n13l".format(app_host,app_port))77 assert 'URL Format is not correct' in str(r.content)...
server.py
Source:server.py
...18 @classmethod19 async def serve(cls):20 loop = asyncio.get_running_loop()21 service = cls()22 host = get_service_host("reducer")23 port = get_service_port("reducer")24 service.setUp()25 server = Server([service], loop=loop)26 print(f'Server running at {host}:{port}')27 await server.start(host, port)28 await server.wait_closed()29 def setUp(self):30 fizz_channel = Channel(get_service_host("fizz"),31 get_service_port("fizz"),32 loop=asyncio.get_running_loop())33 self.fizz_client = FizzStub(fizz_channel)34 buzz_channel = Channel(get_service_host("buzz"),35 get_service_port("buzz"),36 loop=asyncio.get_running_loop())37 self.buzz_client = BuzzStub(buzz_channel)38 async def Ask(self, stream: Stream):39 fizz_result: FizzResponse40 buzz_result: BuzzResponse41 query: ReduceQuery = await stream.recv_message()42 fizz_future = self.fizz_client.Ask(FizzQuery(number=query.number))43 buzz_future = self.buzz_client.Ask(BuzzQuery(number=query.number))44 fizz_result, buzz_result = await asyncio.gather(45 fizz_future,46 buzz_future,47 loop=asyncio.get_running_loop(),48 )49 message = ""50 if fizz_result.isFizz:51 message += "Fizz"52 if buzz_result.isBuzz:53 message += "Buzz"54 await stream.send_message(ReduceResult(message=message))55def get_service_host(service_name: str) -> str:56 return os.environ.get(f"{service_name.upper()}_SERVICE_HOST", "127.0.0.1")57def get_service_port(service_name: str) -> int:58 return int(os.environ.get(f"{service_name.upper()}_SERVICE_PORT", "50051"))59if __name__ == "__main__":...
aws_config.py
Source:aws_config.py
...19 20 def test_get_service_host_found(self):21 '''Test case for ensuring that hosts can be found for existing regions and services.'''22 23 host_name = aws_config.get_service_host("eu-west-1", "sqs")24 25 self.assertEqual("sqs.eu-west-1.amazonaws.com", host_name)26 27 def test_get_service_host_notfound(self):28 '''Test case for ensuring that None is returned when host can not be found.'''29 30 self.assertEqual(None, aws_config.get_service_host(None, None))31 self.assertEqual(None, aws_config.get_service_host("not found", None))32 33 self.assertEqual(None, aws_config.get_service_host("eu-west-1", None))...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!