使用Docker Compose 来运行 Django 的测试

我打算在Django中运行CI时尝试启动Docker并执行测试。

简单的示例

我想连接到Redis等进行测试,所以我使用了Docker Compose,使得只需一条命令就能完成。

使用pip install docker-compose来安装docker-compose。

    docker-composeのconfig
web:
  build: .
  ports:
    - "8000:8000"
  links:
    - redis
  volumes:
    - app:/app
redis:
  image: redis
  ports:
    - "6379:6379"
    webのDockerfile
FROM python:2.7
ADD app /app
WORKDIR /app
RUN pip install django redis
CMD cd /app && python manage.py test

Django只是在启动项目后添加了下面的测试文件。

from django.test import TestCase
import redis


class Test(TestCase):

  def setUp(self):
      self.r = redis.StrictRedis(host="redis")
      self.r.flushdb()

  def test_ok(self):
      self.assertEqual(1, 1)

  def test_error(self):
      self.assertEqual(2, 1)

  def test_redis(self):
      self.assertEqual(self.r.get("name"), None)

      self.r.set("name", "name")
      self.assertEqual(self.r.get("name"), "name")

在样本仓库的部分中,当执行docker-compose run web时,会像下面这样运行测试。我本来想与mysql进行连接,但由于无法连接,所以放弃了。如果不在意数据库是什么的话,使用sqlite3的话可以更快地进行创建,所以测试用sqlite3更好。

$ docker-compose run web

Creating dockerdjangotest_redis_1...
Building web...
Step 0 : FROM python:2.7
 ---> 38960da60ac6
Step 1 : ADD app /app
 ---> 8176a8eb5810
Removing intermediate container f0dcd557a477
Step 2 : WORKDIR /app
 ---> Running in 13b39ca62c46
 ---> 237ded13f022
Removing intermediate container 13b39ca62c46
Step 3 : RUN pip install django redis
 ---> Running in 286f081c5147
You are using pip version 6.0.8, however version 6.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting django
  Downloading Django-1.8-py2.py3-none-any.whl (6.2MB)
Collecting redis
  Downloading redis-2.10.3.tar.gz (86kB)
Installing collected packages: redis, django
  Running setup.py install for redis

Successfully installed django-1.8 redis-2.10.3
 ---> 2e59a3a2bc76
Removing intermediate container 286f081c5147
Step 4 : CMD cd /app && python manage.py test
 ---> Running in f164c5af9ec0
 ---> 49ae601130fb
Removing intermediate container f164c5af9ec0
Successfully built 49ae601130fb
Creating test database for alias 'default'...
F..
======================================================================
FAIL: test_error (app.tests.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/app/app/tests.py", line 15, in test_error
    self.assertEqual(2, 1)
AssertionError: 2 != 1

----------------------------------------------------------------------
Ran 3 tests in 0.006s

FAILED (failures=1)
Destroying test database for alias 'default'...
广告
将在 10 秒后关闭
bannerAds