Skip to content

Instantly share code, notes, and snippets.

@email2liyang
Created March 19, 2019 08:21
Show Gist options
  • Save email2liyang/8acac29671fe98a8f41c4910b8a38c1d to your computer and use it in GitHub Desktop.
Save email2liyang/8acac29671fe98a8f41c4910b8a38c1d to your computer and use it in GitHub Desktop.
docker based unit test with python
import unittest
from datetime import datetime
import docker
class DocerBasedTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
container_name = "test-mysql-" + datetime.now().strftime('%y%m%d%H%M%s')
client = docker.from_env()
api_client = docker.APIClient(base_url='unix://var/run/docker.sock')
client.containers.run("mysql:5.7.25", detach=True, name=container_name,
ports={'3306/tcp': None})
cls._mysql_container = client.containers.get(container_name)
ports = api_client.inspect_container(cls._mysql_container.id)['NetworkSettings']['Ports']
cls._mysql_connection_url = "localhost:{}".format(ports['3306/tcp'][0]['HostPort'])
cls._client = client
@classmethod
def tearDownClass(cls):
cls._mysql_container.remove(force=True)
cls._client.close()
def test_method1(self):
print("mysql connection url is {}".format(self._mysql_connection_url))
self.assertEqual(1, 1, "this is an equal test")
if __name__ == '__main__':
unittest.main()
@email2liyang
Copy link
Author

docker python api is based on https://docker-py.readthedocs.io/en/stable/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment