Docker容器的上下文管理器。
dockerctx的Python项目详细描述
dockerctx
是用于管理Docker容器生存期的上下文管理器。
主要的用例是为运行测试设置脚手架,在需要的地方 比unit tests稍宽一点,但集成度不如, 比如,你可以用Robot framework来写什么。
演示
这是从其中一个测试中获取的:
importtimeimportredisimportpytestfromdockerctximportnew_container# First make a pytest fixture@pytest.fixture(scope='function')deff_redis():# This is the new thing! It's pretty clear. The `ready_test` provides# a way to customize what "ready" means for each container. Here,# we simply pause for a bit.withnew_container(image_name='redis:latest',ports={'6379/tcp':56379},ready_test=lambda:time.sleep(0.5)orTrue)ascontainer:yieldcontainer# Here is the test. Since the fixture is at the "function" level, a fully# new Redis container will be created for each test that uses this fixture.# After the test completes, the container will be removed.deftest_redis_a(f_redis):# The container object comes from the `docker` python package. Here we# access only the "name" attribute, but there are many others.print('Container %s'%f_redis.name)r=redis.StrictRedis(host='localhost',port=56379,db=0)r.set('foo','bar')assertr.get('foo')==b'bar'
注意,这里创建了一个全新的redis容器,用于 上下文管理器的上下文(包装在pytestfixture中 在这里),然后在上下文管理器之后销毁容器 出口。
在src中,还有另一个更详细的测试,它
- 运行postgres容器;
- 等待Postgres开始接受连接;
- 创建数据库;
- 创建表(使用SQLAlchemyorm);
- 执行数据库操作;
- 拆下容器,然后取出。