用 Python 和 Conu 测试容器
容器 测试
![](/data/attachment/album/201811/25/215123sq8nep3nn7ccp13m.jpg)


越来越多的开发人员使用容器开发和部署他们的应用。这意味着可以轻松地测试容器也变得很重要。[Conu](https://github.com/user-cont/conu) (container utilities 的简写) 是一个 Python 库，让你编写容器测试变得简单。本文向你介绍如何使用它测试容器。


### 开始吧


首先，你需要一个容器程序来测试。为此，以下命令创建一个包含一个容器的 Dockerfile 和一个被容器伺服的 Flask 应用程序的文件夹。



```
$ mkdir container_test
$ cd container_test
$ touch Dockerfile
$ touch app.py
```

将以下代码复制到 `app.py` 文件中。这是惯常的基本 Flask 应用，它返回字符串 “Hello Container World！”。



```
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello Container World!'

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0')
```

### 创建和构建测试容器


为了构建测试容器，将以下指令添加到 Dockerfile。



```
FROM registry.fedoraproject.org/fedora-minimal:latest
RUN microdnf -y install python3-flask && microdnf clean all
ADD ./app.py /srv
CMD ["python3", "/srv/app.py"]
```

然后使用 Docker CLI 工具构建容器。



```
$ sudo dnf -y install docker
$ sudo systemctl start docker
$ sudo docker build . -t flaskapp_container
```

提示：只有在系统上未安装 Docker 时才需要前两个命令。


构建之后使用以下命令运行容器。



```
$ sudo docker run -p 5000:5000 --rm flaskapp_container
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 473-505-51
```

最后，使用 `curl` 检查 Flask 应用程序是否在容器内正确运行：



```
$ curl http://127.0.0.1:5000
Hello Container World!
```

现在，flaskapp\_container 正在运行并准备好进行测试，你可以使用 `Ctrl+C` 将其停止。


### 创建测试脚本


在编写测试脚本之前，必须安装 `conu`。在先前创建的 `container_test` 目录中，运行以下命令。



```
$ python3 -m venv .venv
$ source .venv/bin/activate
(.venv)$ pip install --upgrade pip
(.venv)$ pip install conu
$ touch test_container.py
```

然后将以下脚本复制并保存在 `test_container.py` 文件中。



```
import conu

PORT = 5000

with conu.DockerBackend() as backend:
  image = backend.ImageClass("flaskapp_container")
  options = ["-p", "5000:5000"]
  container = image.run_via_binary(additional_opts=options)
  
  try:
    # Check that the container is running and wait for the flask application to start.
    assert container.is_running()
    container.wait_for_port(PORT)
    
    # Run a GET request on / port 5000.
    http_response = container.http_request(path="/", port=PORT)
    
    # Check the response status code is 200
    assert http_response.ok
    
    # Get the response content
    response_content = http_response.content.decode("utf-8")

    # Check that the "Hello Container World!" string is served.
    assert "Hello Container World!" in response_content

    # Get the logs from the container
    logs = [line for line in container.logs()]
    # Check the the Flask application saw the GET request.
    assert b'"GET / HTTP/1.1" 200 -' in logs[-1]

  finally:
    container.stop()
    container.delete()
```

#### 测试设置


这个脚本首先设置 `conu` 使用 Docker 作为后端来运行容器。然后它设置容器镜像以使用你在本教程第一部分中构建的 flaskapp\_container。


下一步是配置运行容器所需的选项。在此示例中，Flask 应用在端口5000上提供内容。于是你需要暴露此端口并将其映射到主机上的同一端口。


最后，用这个脚本启动容器，现在可以测试了。


#### 测试方法


在测试容器之前，检查容器是否正在运行并准备就绪。示范脚本使用 `container.is_running` 和 `container.wait_for_port`。这些方法可确保容器正在运行，并且服务在预设端口上可用。


`container.http_request` 是 [request](http://docs.python-requests.org/en/master/) 库的包装器，可以方便地在测试期间发送 HTTP 请求。这个方法返回[requests.Responseobject](http://docs.python-requests.org/en/master/api/#requests.Response)，因此可以轻松地访问响应的内容以进行测试。


`conu` 还可以访问容器日志。又一次，这在测试期间非常有用。在上面的示例中，`container.logs` 方法返回容器日志。你可以使用它们断言打印了特定日志，或者，例如在测试期间没有异常被引发。


`conu` 提供了许多与容器接合的有用方法。[文档](https://conu.readthedocs.io/en/latest/index.html)中提供了完整的 API 列表。你还可以参考 [GitHub](https://github.com/user-cont/conu/tree/master/docs/source/examples) 上提供的示例。


运行本教程所需的所有代码和文件也可以在 [GitHub](https://github.com/cverna/container_test_script) 上获得。 对于想要进一步采用这个例子的读者，你可以看看使用 [pytest](https://docs.pytest.org/en/latest/) 来运行测试并构建一个容器测试套件。




---


via: <https://fedoramagazine.org/test-containers-python-conu/>


作者：[Clément Verna](https://fedoramagazine.org/author/cverna/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[GraveAccent](https://github.com/GraveAccent) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
More and more developers are using containers to develop and deploy their applications. This means that easily testing containers is also becoming important. [Conu](https://github.com/user-cont/conu) (short for container utilities) is a Python library that makes it easy to write tests for your containers. This article shows you how to use it to test your containers.


## Getting started

First you need a container application to test. For that, the following commands create a new directory with a container *Dockerfile,* and a Flask application to be served by the container.

$mkdir container_test$cd container_test$touch Dockerfile$touch app.py

Copy the following code inside the *app.py *file. This is the customary basic Flask application that returns the string “Hello Container World!”

from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello Container World!' if __name__ == '__main__': app.run(debug=True,host='0.0.0.0')

## Create and Build a Test Container

To build the test container, add the following instructions to the *Dockerfile*.

FROM registry.fedoraproject.org/fedora-minimal:latest RUN microdnf -y install python3-flask && microdnf clean all ADD ./app.py /srv CMD ["python3", "/srv/app.py"]

Then build the container using the Docker CLI tool.

$sudo dnf -y install docker$sudo systemctl start docker$sudo docker build . -t flaskapp_container

Note : The first two commands are only needed if Docker is not installed on your system.

After the build use the following command to run the container.

$sudo docker run -p 5000:5000 --rm flaskapp_container* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 473-505-51

Finally, use *curl* to check that the Flask application is correctly running inside the container:

$ curl http://127.0.0.1:5000 Hello Container World!

With the *flaskapp_container* now running and ready for testing, you can stop it using **Ctrl+C**.

## Create a test script

Before you write the test script, you must install *conu*. Inside the previously created *container_test* directory run the following commands.

$python3 -m venv .venv$source .venv/bin/activate(.venv)$pip install --upgrade pip(.venv)$pip install conu$touch test_container.py

Then copy and save the following script in the *test_container.py * file.

import conu PORT = 5000 with conu.DockerBackend() as backend: image = backend.ImageClass("flaskapp_container") options = ["-p", "5000:5000"] container = image.run_via_binary(additional_opts=options) try: # Check that the container is running and wait for the flask application to start. assert container.is_running() container.wait_for_port(PORT) # Run a GET request on / port 5000. http_response = container.http_request(path="/", port=PORT) # Check the response status code is 200 assert http_response.ok # Get the response content response_content = http_response.content.decode("utf-8") # Check that the "Hello Container World!" string is served. assert "Hello Container World!" in response_content # Get the logs from the container logs = [line for line in container.logs()] # Check the the Flask application saw the GET request. assert b'"GET / HTTP/1.1" 200 -' in logs[-1] finally: container.stop() container.delete()

### Test Setup

The script starts by setting *conu* to use Docker as a backend to run the container. Then it sets the container image to use the *flaskapp_container* you built in the first part of this tutorial.

The next step is to configure the options needed to run the container. In this example, the Flask application serves the content on port 5000. Therefore you need to expose this port and map it to the same port on the host.

Finally, the script starts the container, and it’s now ready to be tested.

### Testing methods

Before testing a container, check that the container is running and ready. The example script is using *container.is_running* and *container.wait_for_port.* These methods ensure the container is running and the service is available on the expected port.

The *container.**http_request * is a wrapper around the [ requests](http://docs.python-requests.org/en/master/) library which makes it convenient to send HTTP requests during the tests. This method returns a

[object, so it’s easy to access the content of the response for testing.](http://docs.python-requests.org/en/master/api/#requests.Response)

*requests.Response*Conu also gives access to the container logs. Once again, this can be useful during testing. In the example above, the *container.logs *method returns the container logs. You can use them to assert that a specific log was printed, or for example that no exceptions were raised during testing.

*Conu *provides many other useful methods to interface with containers. A full list of the APIs is available in the [documentation](https://conu.readthedocs.io/en/latest/index.html). You can also consult the examples available on [GitHub](https://github.com/user-cont/conu/tree/master/docs/source/examples).

All the code and files needed to run this tutorial are available on [GitHub](https://github.com/cverna/container_test_script) as well. For readers who want to take this example further, you can look at using [pytest](https://docs.pytest.org/en/latest/) to run the tests and build a container test suite.

## Pavan Sapkal

can we test other application using conu except container of docker ?

## Clément Verna

There are other backends available so you can test containers using a Kubernestes backend for example (see here https://github.com/user-cont/conu#kubernetes)