From acd2607407d9b01150f0fb167aa3b6e036ccb82a Mon Sep 17 00:00:00 2001 From: shin- Date: Tue, 15 Oct 2013 21:15:01 +0200 Subject: [PATCH] Flake8 compliance + flake8 tests in tox.ini --- docker/__init__.py | 2 +- docker/auth/__init__.py | 10 +++- docker/client.py | 84 ++++++++++++++++++++-------------- docker/unixconn/__init__.py | 2 +- docker/utils/__init__.py | 2 +- tests/fake_api.py | 91 +++++++++++++++++++++++++------------ tests/integration_test.py | 60 +++++++++++++++++++----- tests/test.py | 89 +++++++++++++++++++++++++----------- tox.ini | 8 +++- 9 files changed, 242 insertions(+), 106 deletions(-) diff --git a/docker/__init__.py b/docker/__init__.py index 96338bb0..5f642a85 100644 --- a/docker/__init__.py +++ b/docker/__init__.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -from .client import Client, APIError +from .client import Client, APIError # flake8: noqa diff --git a/docker/auth/__init__.py b/docker/auth/__init__.py index d7c8ad39..90c90298 100644 --- a/docker/auth/__init__.py +++ b/docker/auth/__init__.py @@ -1 +1,9 @@ -from .auth import * \ No newline at end of file + + +from .auth import ( + INDEX_URL, + encode_header, + load_config, + resolve_authconfig, + resolve_repository_name +) # flake8: noqa \ No newline at end of file diff --git a/docker/client.py b/docker/client.py index f6e6fb40..3da7353b 100644 --- a/docker/client.py +++ b/docker/client.py @@ -31,7 +31,7 @@ class APIError(requests.exceptions.HTTPError): self.explanation = explanation - if self.explanation is None and response.content and len(response.content) > 0: + if self.explanation is None and response.content: self.explanation = response.content.strip() def __str__(self): @@ -86,13 +86,15 @@ class Client(requests.Session): return response.text def _container_config(self, image, command, hostname=None, user=None, - detach=False, stdin_open=False, tty=False, mem_limit=0, ports=None, - environment=None, dns=None, volumes=None, volumes_from=None, - privileged=False): + detach=False, stdin_open=False, tty=False, + mem_limit=0, ports=None, environment=None, dns=None, + volumes=None, volumes_from=None, privileged=False): if isinstance(command, six.string_types): command = shlex.split(str(command)) if isinstance(environment, dict): - environment = ['{0}={1}'.format(k, v) for k, v in environment.items()] + environment = [ + '{0}={1}'.format(k, v) for k, v in environment.items() + ] attach_stdin = False attach_stdout = False @@ -166,25 +168,31 @@ class Client(requests.Session): else: break - def build(self, path=None, tag=None, quiet=False, fileobj=None, nocache=False, rm=False): + def build(self, path=None, tag=None, quiet=False, fileobj=None, + nocache=False, rm=False): remote = context = headers = None if path is None and fileobj is None: raise Exception("Either path or fileobj needs to be provided.") if fileobj is not None: context = utils.mkbuildcontext(fileobj) - elif (path.startswith('http://') or path.startswith('https://') or - path.startswith('git://') or path.startswith('github.com/')): + elif path.startswith(('http://', 'https://', 'git://', 'github.com/')): remote = path else: context = utils.tar(path) u = self._url('/build') - params = { 't': tag, 'remote': remote, 'q': quiet, 'nocache': nocache, 'rm': rm } + params = { + 't': tag, + 'remote': remote, + 'q': quiet, + 'nocache': nocache, + 'rm': rm + } if context is not None: - headers = { 'Content-Type': 'application/tar' } + headers = {'Content-Type': 'application/tar'} res = self._result(self.post(u, context, params=params, - headers=headers, stream=True)) + headers=headers, stream=True)) if context is not None: context.close() srch = r'Successfully built ([0-9a-f]+)' @@ -194,7 +202,7 @@ class Client(requests.Session): return match.group(1), res def commit(self, container, repository=None, tag=None, message=None, - author=None, conf=None): + author=None, conf=None): params = { 'container': container, 'repo': repository, @@ -206,7 +214,7 @@ class Client(requests.Session): return self._result(self._post_json(u, conf, params=params), json=True) def containers(self, quiet=False, all=False, trunc=True, latest=False, - since=None, before=None, limit=-1): + since=None, before=None, limit=-1): params = { 'limit': 1 if latest else limit, 'all': 1 if all else 0, @@ -217,25 +225,27 @@ class Client(requests.Session): u = self._url("/containers/ps") res = self._result(self.get(u, params=params), True) if quiet: - return [{ 'Id': x['Id'] } for x in res] + return [{'Id': x['Id']} for x in res] return res def copy(self, container, resource): - res = self._post_json(self._url("/containers/{0}/copy".format(container)), + res = self._post_json( + self._url("/containers/{0}/copy".format(container)), {"Resource": resource}, - stream=True) + stream=True + ) self._raise_for_status(res) return res.raw def create_container(self, image, command, hostname=None, user=None, - detach=False, stdin_open=False, tty=False, mem_limit=0, ports=None, - environment=None, dns=None, volumes=None, volumes_from=None, - privileged=False): + detach=False, stdin_open=False, tty=False, + mem_limit=0, ports=None, environment=None, dns=None, + volumes=None, volumes_from=None, privileged=False): - - config = self._container_config(image, command, hostname, user, - detach, stdin_open, tty, mem_limit, ports, environment, dns, - volumes, volumes_from, privileged) + config = self._container_config( + image, command, hostname, user, detach, stdin_open, tty, mem_limit, + ports, environment, dns, volumes, volumes_from, privileged + ) return self.create_container_from_config(config) def create_container_from_config(self, config): @@ -247,13 +257,13 @@ class Client(requests.Session): if isinstance(container, dict): container = container.get('Id') return self._result(self.get(self._url("/containers/{0}/changes". - format(container))), True) + format(container))), True) def export(self, container): if isinstance(container, dict): container = container.get('Id') res = self.get(self._url("/containers/{0}/export".format(container)), - stream=True) + stream=True) self._raise_for_status(res) return res.raw @@ -271,7 +281,7 @@ class Client(requests.Session): 'all': 1 if all else 0, } res = self._result(self.get(self._url("/images/json"), params=params), - True) + True) if quiet: return [x['Id'] for x in res] return res @@ -312,12 +322,14 @@ class Client(requests.Session): def inspect_container(self, container): if isinstance(container, dict): container = container.get('Id') - return self._result(self.get(self._url("/containers/{0}/json". - format(container))), True) + return self._result(self.get( + self._url("/containers/{0}/json".format(container)) + ), True) def inspect_image(self, image_id): - return self._result(self.get(self._url("/images/{0}/json". - format(image_id))), True) + return self._result(self.get( + self._url("/images/{0}/json".format(image_id)) + ), True) def kill(self, container): if isinstance(container, dict): @@ -411,7 +423,7 @@ class Client(requests.Session): def remove_container(self, container, v=False): if isinstance(container, dict): container = container.get('Id') - params = { 'v': v } + params = {'v': v} res = self.delete(self._url("/containers/" + container), params=params) self._raise_for_status(res) @@ -422,14 +434,14 @@ class Client(requests.Session): def restart(self, container, timeout=10): if isinstance(container, dict): container = container.get('Id') - params = { 't': timeout } + params = {'t': timeout} url = self._url("/containers/{0}/restart".format(container)) res = self.post(url, None, params=params) self._raise_for_status(res) def search(self, term): return self._result(self.get(self._url("/images/search"), - params={'term': term}), True) + params={'term': term}), True) def start(self, container, binds=None, lxc_conf=None): if isinstance(container, dict): @@ -438,7 +450,9 @@ class Client(requests.Session): 'LxcConf': lxc_conf } if binds: - bind_pairs = ['{0}:{1}'.format(host, dest) for host, dest in binds.items()] + bind_pairs = [ + '{0}:{1}'.format(host, dest) for host, dest in binds.items() + ] start_config['Binds'] = bind_pairs url = self._url("/containers/{0}/start".format(container)) @@ -448,7 +462,7 @@ class Client(requests.Session): def stop(self, container, timeout=10): if isinstance(container, dict): container = container.get('Id') - params = { 't': timeout } + params = {'t': timeout} url = self._url("/containers/{0}/stop".format(container)) res = self.post(url, None, params=params) self._raise_for_status(res) diff --git a/docker/unixconn/__init__.py b/docker/unixconn/__init__.py index cfd7c3e9..53711fc6 100644 --- a/docker/unixconn/__init__.py +++ b/docker/unixconn/__init__.py @@ -1 +1 @@ -from .unixconn import UnixAdapter +from .unixconn import UnixAdapter # flake8: noqa diff --git a/docker/utils/__init__.py b/docker/utils/__init__.py index 91e90125..391eb2ee 100644 --- a/docker/utils/__init__.py +++ b/docker/utils/__init__.py @@ -1 +1 @@ -from .utils import mkbuildcontext, tar, compare_version +from .utils import mkbuildcontext, tar, compare_version # flake8: noqa diff --git a/tests/fake_api.py b/tests/fake_api.py index ab4fc39b..1c611daa 100644 --- a/tests/fake_api.py +++ b/tests/fake_api.py @@ -1,4 +1,16 @@ -import json +# Copyright 2013 dotCloud inc. + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. CURRENT_VERSION = 'v1.4' @@ -30,21 +42,24 @@ def get_fake_search(): def get_fake_images(): status_code = 200 - response = [ - {'Id': FAKE_IMAGE_ID, 'Created': '2 days ago', 'Repository': 'busybox', 'Tag': 'latest'} - ] + response = [{ + 'Id': FAKE_IMAGE_ID, + 'Created': '2 days ago', + 'Repository': 'busybox', + 'Tag': 'latest' + }] return status_code, response def get_fake_containers(): status_code = 200 - response = [ - {'Id': FAKE_CONTAINER_ID, + response = [{ + 'Id': FAKE_CONTAINER_ID, 'Image': 'busybox:latest', 'Created': '2 days ago', 'Command': 'true', - 'Status': 'fake status'} - ] + 'Status': 'fake status' + }] return status_code, response @@ -67,7 +82,7 @@ def get_fake_inspect_container(): 'Config': {'Privileged': True}, 'ID': FAKE_CONTAINER_ID, 'Image': 'busybox:latest', - "State": { + "State": { "Running": True, "Pid": 0, "ExitCode": 0, @@ -145,24 +160,44 @@ def post_fake_build_container(): ## maps real api url to fake response callback +prefix = 'unix://var/run/docker.sock' fake_responses = { - 'unix://var/run/docker.sock/{0}/version'.format(CURRENT_VERSION): get_fake_version, - 'unix://var/run/docker.sock/{0}/info'.format(CURRENT_VERSION): get_fake_info, - 'unix://var/run/docker.sock/{0}/images/search'.format(CURRENT_VERSION): get_fake_search, - 'unix://var/run/docker.sock/{0}/images/json'.format(CURRENT_VERSION): get_fake_images, - 'unix://var/run/docker.sock/{0}/containers/ps'.format(CURRENT_VERSION): get_fake_containers, - 'unix://var/run/docker.sock/{0}/containers/3cc2351ab11b/start'.format(CURRENT_VERSION): post_fake_start_container, - 'unix://var/run/docker.sock/{0}/containers/3cc2351ab11b/json'.format(CURRENT_VERSION): get_fake_inspect_container, - 'unix://var/run/docker.sock/{0}/containers/3cc2351ab11b/wait'.format(CURRENT_VERSION): get_fake_wait, - 'unix://var/run/docker.sock/{0}/containers/3cc2351ab11b/attach'.format(CURRENT_VERSION): get_fake_logs, - 'unix://var/run/docker.sock/{0}/containers/3cc2351ab11b/changes'.format(CURRENT_VERSION): get_fake_diff, - 'unix://var/run/docker.sock/{0}/containers/3cc2351ab11b/stop'.format(CURRENT_VERSION): post_fake_stop_container, - 'unix://var/run/docker.sock/{0}/containers/3cc2351ab11b/kill'.format(CURRENT_VERSION): post_fake_kill_container, - 'unix://var/run/docker.sock/{0}/containers/3cc2351ab11b/restart'.format(CURRENT_VERSION): post_fake_restart_container, - 'unix://var/run/docker.sock/{0}/containers/3cc2351ab11b'.format(CURRENT_VERSION): delete_fake_remove_container, - 'unix://var/run/docker.sock/{0}/images/create'.format(CURRENT_VERSION): post_fake_image_create, - 'unix://var/run/docker.sock/{0}/images/e9aa60c60128'.format(CURRENT_VERSION): delete_fake_remove_image, - 'unix://var/run/docker.sock/{0}/commit'.format(CURRENT_VERSION): post_fake_commit, - 'unix://var/run/docker.sock/{0}/containers/create'.format(CURRENT_VERSION): post_fake_create_container, - 'unix://var/run/docker.sock/{0}/build'.format(CURRENT_VERSION): post_fake_build_container + '{1}/{0}/version'.format(CURRENT_VERSION, prefix): + get_fake_version, + '{1}/{0}/info'.format(CURRENT_VERSION, prefix): + get_fake_info, + '{1}/{0}/images/search'.format(CURRENT_VERSION, prefix): + get_fake_search, + '{1}/{0}/images/json'.format(CURRENT_VERSION, prefix): + get_fake_images, + '{1}/{0}/containers/ps'.format(CURRENT_VERSION, prefix): + get_fake_containers, + '{1}/{0}/containers/3cc2351ab11b/start'.format(CURRENT_VERSION, prefix): + post_fake_start_container, + '{1}/{0}/containers/3cc2351ab11b/json'.format(CURRENT_VERSION, prefix): + get_fake_inspect_container, + '{1}/{0}/containers/3cc2351ab11b/wait'.format(CURRENT_VERSION, prefix): + get_fake_wait, + '{1}/{0}/containers/3cc2351ab11b/attach'.format(CURRENT_VERSION, prefix): + get_fake_logs, + '{1}/{0}/containers/3cc2351ab11b/changes'.format(CURRENT_VERSION, prefix): + get_fake_diff, + '{1}/{0}/containers/3cc2351ab11b/stop'.format(CURRENT_VERSION, prefix): + post_fake_stop_container, + '{1}/{0}/containers/3cc2351ab11b/kill'.format(CURRENT_VERSION, prefix): + post_fake_kill_container, + '{1}/{0}/containers/3cc2351ab11b/restart'.format(CURRENT_VERSION, prefix): + post_fake_restart_container, + '{1}/{0}/containers/3cc2351ab11b'.format(CURRENT_VERSION, prefix): + delete_fake_remove_container, + '{1}/{0}/images/create'.format(CURRENT_VERSION, prefix): + post_fake_image_create, + '{1}/{0}/images/e9aa60c60128'.format(CURRENT_VERSION, prefix): + delete_fake_remove_image, + '{1}/{0}/commit'.format(CURRENT_VERSION, prefix): + post_fake_commit, + '{1}/{0}/containers/create'.format(CURRENT_VERSION, prefix): + post_fake_create_container, + '{1}/{0}/build'.format(CURRENT_VERSION, prefix): + post_fake_build_container } diff --git a/tests/integration_test.py b/tests/integration_test.py index 59c78099..bc722f9b 100644 --- a/tests/integration_test.py +++ b/tests/integration_test.py @@ -13,8 +13,8 @@ # limitations under the License. import base64 -import os import io +import os import tempfile import unittest @@ -52,6 +52,7 @@ class BaseTestCase(unittest.TestCase): ## INFORMATION TESTS ## ######################### + class TestVersion(BaseTestCase): def runTest(self): res = self.client.version() @@ -59,6 +60,7 @@ class TestVersion(BaseTestCase): self.assertIn('Version', res) self.assertEqual(len(res['Version'].split('.')), 3) + class TestInfo(BaseTestCase): def runTest(self): res = self.client.info() @@ -66,6 +68,7 @@ class TestInfo(BaseTestCase): self.assertIn('Images', res) self.assertIn('Debug', res) + class TestSearch(BaseTestCase): def runTest(self): res = self.client.search('busybox') @@ -78,6 +81,7 @@ class TestSearch(BaseTestCase): ## LISTING TESTS ## ################### + class TestImages(BaseTestCase): def runTest(self): res1 = self.client.images(all=True) @@ -94,11 +98,13 @@ class TestImages(BaseTestCase): distinct.append(img['Id']) self.assertEqual(len(distinct), self.client.info()['Images']) + class TestImageIds(BaseTestCase): def runTest(self): res1 = self.client.images(quiet=True) self.assertEqual(type(res1[0]), six.text_type) + class TestListContainers(BaseTestCase): def runTest(self): res0 = self.client.containers(all=True) @@ -122,12 +128,14 @@ class TestListContainers(BaseTestCase): ## CONTAINER TESTS ## ##################### + class TestCreateContainer(BaseTestCase): def runTest(self): res = self.client.create_container('busybox', 'true') self.assertIn('Id', res) self.tmp_containers.append(res['Id']) + class TestCreateContainerWithBinds(BaseTestCase): def runTest(self): mount_dest = '/mnt' @@ -137,8 +145,10 @@ class TestCreateContainerWithBinds(BaseTestCase): shared_file = os.path.join(mount_origin, filename) with open(shared_file, 'w'): - container = self.client.create_container('busybox', - ['ls', mount_dest], volumes={mount_dest: {}}) + container = self.client.create_container( + 'busybox', + ['ls', mount_dest], volumes={mount_dest: {}} + ) container_id = container['Id'] self.client.start(container_id, binds={mount_origin: mount_dest}) self.tmp_containers.append(container_id) @@ -149,6 +159,7 @@ class TestCreateContainerWithBinds(BaseTestCase): os.unlink(shared_file) self.assertIn(filename, logs) + class TestCreateContainerPrivileged(BaseTestCase): def runTest(self): res = self.client.create_container('busybox', 'true', privileged=True) @@ -156,6 +167,7 @@ class TestCreateContainerPrivileged(BaseTestCase): self.assertIn('Config', inspect) self.assertEqual(inspect['Config']['Privileged'], True) + class TestStartContainer(BaseTestCase): def runTest(self): res = self.client.create_container('busybox', 'true') @@ -173,6 +185,7 @@ class TestStartContainer(BaseTestCase): self.assertIn('ExitCode', inspect['State']) self.assertEqual(inspect['State']['ExitCode'], 0) + class TestStartContainerWithDictInsteadOfId(BaseTestCase): def runTest(self): res = self.client.create_container('busybox', 'true') @@ -190,6 +203,7 @@ class TestStartContainerWithDictInsteadOfId(BaseTestCase): self.assertIn('ExitCode', inspect['State']) self.assertEqual(inspect['State']['ExitCode'], 0) + class TestWait(BaseTestCase): def runTest(self): res = self.client.create_container('busybox', ['sleep', '10']) @@ -204,6 +218,7 @@ class TestWait(BaseTestCase): self.assertIn('ExitCode', inspect['State']) self.assertEqual(inspect['State']['ExitCode'], exitcode) + class TestWaitWithDictInsteadOfId(BaseTestCase): def runTest(self): res = self.client.create_container('busybox', ['sleep', '10']) @@ -218,11 +233,13 @@ class TestWaitWithDictInsteadOfId(BaseTestCase): self.assertIn('ExitCode', inspect['State']) self.assertEqual(inspect['State']['ExitCode'], exitcode) + class TestLogs(BaseTestCase): def runTest(self): snippet = 'Flowering Nights (Sakuya Iyazoi)' - container = self.client.create_container('busybox', - 'echo {0}'.format(snippet)) + container = self.client.create_container( + 'busybox', 'echo {0}'.format(snippet) + ) id = container['Id'] self.client.start(id) self.tmp_containers.append(id) @@ -231,11 +248,13 @@ class TestLogs(BaseTestCase): logs = self.client.logs(id) self.assertEqual(logs, snippet + '\n') + class TestLogsWithDictInsteadOfId(BaseTestCase): def runTest(self): snippet = 'Flowering Nights (Sakuya Iyazoi)' - container = self.client.create_container('busybox', - 'echo {0}'.format(snippet)) + container = self.client.create_container( + 'busybox', 'echo {0}'.format(snippet) + ) id = container['Id'] self.client.start(id) self.tmp_containers.append(id) @@ -244,6 +263,7 @@ class TestLogsWithDictInsteadOfId(BaseTestCase): logs = self.client.logs(container) self.assertEqual(logs, snippet + '\n') + class TestDiff(BaseTestCase): def runTest(self): container = self.client.create_container('busybox', ['touch', '/test']) @@ -258,6 +278,7 @@ class TestDiff(BaseTestCase): self.assertIn('Kind', test_diff[0]) self.assertEqual(test_diff[0]['Kind'], 1) + class TestDiffWithDictInsteadOfId(BaseTestCase): def runTest(self): container = self.client.create_container('busybox', ['touch', '/test']) @@ -272,6 +293,7 @@ class TestDiffWithDictInsteadOfId(BaseTestCase): self.assertIn('Kind', test_diff[0]) self.assertEqual(test_diff[0]['Kind'], 1) + class TestStop(BaseTestCase): def runTest(self): container = self.client.create_container('busybox', ['sleep', '9999']) @@ -287,6 +309,7 @@ class TestStop(BaseTestCase): self.assertIn('Running', state) self.assertEqual(state['Running'], False) + class TestStopWithDictInsteadOfId(BaseTestCase): def runTest(self): container = self.client.create_container('busybox', ['sleep', '9999']) @@ -303,6 +326,7 @@ class TestStopWithDictInsteadOfId(BaseTestCase): self.assertIn('Running', state) self.assertEqual(state['Running'], False) + class TestKill(BaseTestCase): def runTest(self): container = self.client.create_container('busybox', ['sleep', '9999']) @@ -318,6 +342,7 @@ class TestKill(BaseTestCase): self.assertIn('Running', state) self.assertEqual(state['Running'], False) + class TestKillWithDictInsteadOfId(BaseTestCase): def runTest(self): container = self.client.create_container('busybox', ['sleep', '9999']) @@ -333,6 +358,7 @@ class TestKillWithDictInsteadOfId(BaseTestCase): self.assertIn('Running', state) self.assertEqual(state['Running'], False) + class TestRestart(BaseTestCase): def runTest(self): container = self.client.create_container('busybox', ['sleep', '9999']) @@ -353,6 +379,7 @@ class TestRestart(BaseTestCase): self.assertEqual(info2['State']['Running'], True) self.client.kill(id) + class TestRestartWithDictInsteadOfId(BaseTestCase): def runTest(self): container = self.client.create_container('busybox', ['sleep', '9999']) @@ -374,6 +401,7 @@ class TestRestartWithDictInsteadOfId(BaseTestCase): self.assertEqual(info2['State']['Running'], True) self.client.kill(id) + class TestRemoveContainer(BaseTestCase): def runTest(self): container = self.client.create_container('busybox', ['true']) @@ -385,6 +413,7 @@ class TestRemoveContainer(BaseTestCase): res = [x for x in containers if 'Id' in x and x['Id'].startswith(id)] self.assertEqual(len(res), 0) + class TestRemoveContainerWithDictInsteadOfId(BaseTestCase): def runTest(self): container = self.client.create_container('busybox', ['true']) @@ -400,6 +429,7 @@ class TestRemoveContainerWithDictInsteadOfId(BaseTestCase): ## IMAGES TESTS ## ################## + class TestPull(BaseTestCase): def runTest(self): try: @@ -418,6 +448,7 @@ class TestPull(BaseTestCase): self.tmp_imgs.append('joffrey/test001') self.tmp_imgs.append('376968a23351') + class TestCommit(BaseTestCase): def runTest(self): container = self.client.create_container('busybox', ['touch', '/test']) @@ -458,6 +489,7 @@ class TestRemoveImage(BaseTestCase): # BUILDER TESTS # ################# + class TestBuild(BaseTestCase): def runTest(self): script = io.BytesIO('\n'.join([ @@ -465,7 +497,8 @@ class TestBuild(BaseTestCase): 'MAINTAINER docker-py', 'RUN mkdir -p /tmp/test', 'EXPOSE 8080', - 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz /tmp/silence.tar.gz' + 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz' + ' /tmp/silence.tar.gz' ]).encode('ascii')) img, logs = self.client.build(fileobj=script) self.assertNotEqual(img, None) @@ -495,7 +528,8 @@ class TestBuildFromStringIO(BaseTestCase): 'MAINTAINER docker-py', 'RUN mkdir -p /tmp/test', 'EXPOSE 8080', - 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz /tmp/silence.tar.gz' + 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz' + ' /tmp/silence.tar.gz' ])) img, logs = self.client.build(fileobj=script) self.assertNotEqual(img, None) @@ -519,12 +553,15 @@ class TestBuildFromStringIO(BaseTestCase): ## PY SPECIFIC TESTS ## ####################### + class TestRunShlex(BaseTestCase): def runTest(self): commands = [ 'true', - 'echo "The Young Descendant of Tepes & Septette for the Dead Princess"', - 'echo -n "The Young Descendant of Tepes & Septette for the Dead Princess"', + 'echo "The Young Descendant of Tepes & Septette for the ' + 'Dead Princess"', + 'echo -n "The Young Descendant of Tepes & Septette for the ' + 'Dead Princess"', '/bin/sh -c "echo Hello World"', '/bin/sh -c \'echo "Hello World"\'', 'echo "\"Night of Nights\""', @@ -538,6 +575,7 @@ class TestRunShlex(BaseTestCase): exitcode = self.client.wait(id) self.assertEqual(exitcode, 0, msg=cmd) + class TestLoadConfig(BaseTestCase): def runTest(self): folder = tempfile.mkdtemp() diff --git a/tests/test.py b/tests/test.py index 01572a36..f06d76eb 100644 --- a/tests/test.py +++ b/tests/test.py @@ -60,7 +60,8 @@ def fake_resp(url, data=None, **kwargs): fake_request = mock.Mock(side_effect=fake_resp) -@mock.patch.multiple('docker.Client', get=fake_request, post=fake_request, put=fake_request, delete=fake_request) +@mock.patch.multiple('docker.Client', get=fake_request, post=fake_request, + put=fake_request, delete=fake_request) class DockerClientTest(unittest.TestCase): def setUp(self): self.client = docker.Client() @@ -74,7 +75,9 @@ class DockerClientTest(unittest.TestCase): except Exception as e: self.fail('Command should not raise exception: {0}'.format(e)) - fake_request.assert_called_with('unix://var/run/docker.sock/v1.4/version') + fake_request.assert_called_with( + 'unix://var/run/docker.sock/v1.4/version' + ) def test_info(self): try: @@ -90,8 +93,10 @@ class DockerClientTest(unittest.TestCase): except Exception as e: self.fail('Command should not raise exception: {0}'.format(e)) - fake_request.assert_called_with('unix://var/run/docker.sock/v1.4/images/search', - params={'term': 'busybox'}) + fake_request.assert_called_with( + 'unix://var/run/docker.sock/v1.4/images/search', + params={'term': 'busybox'} + ) ################### ## LISTING TESTS ## @@ -102,8 +107,10 @@ class DockerClientTest(unittest.TestCase): self.client.images(all=True) except Exception as e: self.fail('Command should not raise exception: {0}'.format(e)) - fake_request.assert_called_with('unix://var/run/docker.sock/v1.4/images/json', - params={'filter': None, 'only_ids': 0, 'all': 1}) + fake_request.assert_called_with( + 'unix://var/run/docker.sock/v1.4/images/json', + params={'filter': None, 'only_ids': 0, 'all': 1} + ) def test_image_ids(self): try: @@ -111,8 +118,10 @@ class DockerClientTest(unittest.TestCase): except Exception as e: self.fail('Command should not raise exception: {0}'.format(e)) - fake_request.assert_called_with('unix://var/run/docker.sock/v1.4/images/json', - params={'filter': None, 'only_ids': 1, 'all': 0}) + fake_request.assert_called_with( + 'unix://var/run/docker.sock/v1.4/images/json', + params={'filter': None, 'only_ids': 1, 'all': 0} + ) def test_list_containers(self): try: @@ -120,7 +129,8 @@ class DockerClientTest(unittest.TestCase): except Exception as e: self.fail('Command should not raise exception: {0}'.format(e)) - fake_request.assert_called_with('unix://var/run/docker.sock/v1.4/containers/ps', + fake_request.assert_called_with( + 'unix://var/run/docker.sock/v1.4/containers/ps', params={ 'all': 1, 'since': None, @@ -141,35 +151,57 @@ class DockerClientTest(unittest.TestCase): self.fail('Command should not raise exception: {0}'.format(e)) args = fake_request.call_args - self.assertEqual(args[0][0], 'unix://var/run/docker.sock/v1.4/containers/create') - self.assertEqual(json.loads(args[0][1]), json.loads('{"Tty": false, "Image": "busybox", "Cmd": ["true"], "AttachStdin": false, "Memory": 0, "AttachStderr": true, "Privileged": false, "AttachStdout": true, "OpenStdin": false}')) - self.assertEqual(args[1]['headers'], {'Content-Type': 'application/json'}) + self.assertEqual(args[0][0], + 'unix://var/run/docker.sock/v1.4/containers/create') + self.assertEqual(json.loads(args[0][1]), + json.loads(''' + {"Tty": false, "Image": "busybox", "Cmd": ["true"], + "AttachStdin": false, "Memory": 0, + "AttachStderr": true, "Privileged": false, + "AttachStdout": true, "OpenStdin": false}''')) + self.assertEqual(args[1]['headers'], + {'Content-Type': 'application/json'}) def test_create_container_with_binds(self): mount_dest = '/mnt' - mount_origin = '/tmp' + #mount_origin = '/tmp' try: - self.client.create_container('busybox', - ['ls', mount_dest], volumes={mount_dest: {}}) + self.client.create_container('busybox', ['ls', mount_dest], + volumes={mount_dest: {}}) except Exception as e: self.fail('Command should not raise exception: {0}'.format(e)) args = fake_request.call_args - self.assertEqual(args[0][0], 'unix://var/run/docker.sock/v1.4/containers/create') - self.assertEqual(json.loads(args[0][1]), json.loads('{"Tty": false, "Image": "busybox", "Cmd": ["ls", "/mnt"], "AttachStdin": false, "Volumes": {"/mnt": {}}, "Memory": 0, "AttachStderr": true, "Privileged": false, "AttachStdout": true, "OpenStdin": false}')) - self.assertEqual(args[1]['headers'], {'Content-Type': 'application/json'}) + self.assertEqual(args[0][0], + 'unix://var/run/docker.sock/v1.4/containers/create') + self.assertEqual(json.loads(args[0][1]), + json.loads(''' + {"Tty": false, "Image": "busybox", + "Cmd": ["ls", "/mnt"], "AttachStdin": false, + "Volumes": {"/mnt": {}}, "Memory": 0, + "AttachStderr": true, "Privileged": false, + "AttachStdout": true, "OpenStdin": false}''')) + self.assertEqual(args[1]['headers'], + {'Content-Type': 'application/json'}) def test_create_container_privileged(self): try: self.client.create_container('busybox', 'true', privileged=True) except Exception as e: self.fail('Command should not raise exception: {0}'.format(e)) - + args = fake_request.call_args - self.assertEqual(args[0][0], 'unix://var/run/docker.sock/v1.4/containers/create') - self.assertEqual(json.loads(args[0][1]), json.loads('{"Tty": false, "Image": "busybox", "Cmd": ["true"], "AttachStdin": false, "Memory": 0, "AttachStderr": true, "Privileged": true, "AttachStdout": true, "OpenStdin": false}')) - self.assertEqual(args[1]['headers'], {'Content-Type': 'application/json'}) + self.assertEqual(args[0][0], + 'unix://var/run/docker.sock/v1.4/containers/create') + self.assertEqual(json.loads(args[0][1]), + json.loads(''' + {"Tty": false, "Image": "busybox", "Cmd": ["true"], + "AttachStdin": false, "Memory": 0, + "AttachStderr": true, "Privileged": true, + "AttachStdout": true, "OpenStdin": false}''')) + self.assertEqual(args[1]['headers'], + {'Content-Type': 'application/json'}) def test_start_container(self): try: @@ -187,7 +219,8 @@ class DockerClientTest(unittest.TestCase): try: mount_dest = '/mnt' mount_origin = '/tmp' - self.client.start(fake_api.FAKE_CONTAINER_ID, binds={mount_origin: mount_dest}) + self.client.start(fake_api.FAKE_CONTAINER_ID, + binds={mount_origin: mount_dest}) except Exception as e: self.fail('Command should not raise exception: {0}'.format(e)) @@ -375,7 +408,8 @@ class DockerClientTest(unittest.TestCase): except Exception as e: self.fail('Command should not raise exception: {0}'.format(e)) - fake_request.assert_called_with('unix://var/run/docker.sock/v1.4/images/create', + fake_request.assert_called_with( + 'unix://var/run/docker.sock/v1.4/images/create', headers={}, params={'tag': None, 'fromImage': 'joffrey/test001'} ) @@ -405,7 +439,9 @@ class DockerClientTest(unittest.TestCase): except Exception as e: self.fail('Command should not raise exception: {0}'.format(e)) - fake_request.assert_called_with('unix://var/run/docker.sock/v1.4/images/e9aa60c60128') + fake_request.assert_called_with( + 'unix://var/run/docker.sock/v1.4/images/e9aa60c60128' + ) ################# # BUILDER TESTS # @@ -417,7 +453,8 @@ class DockerClientTest(unittest.TestCase): 'MAINTAINER docker-py', 'RUN mkdir -p /tmp/test', 'EXPOSE 8080', - 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz /tmp/silence.tar.gz' + 'ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz' + ' /tmp/silence.tar.gz' ]).encode('ascii')) try: self.client.build(fileobj=script) diff --git a/tox.ini b/tox.ini index 12b033e2..f25f9236 100644 --- a/tox.ini +++ b/tox.ini @@ -1,9 +1,13 @@ [tox] -envlist = py26, py27, py32, py33 +envlist = py26, py27, py32, py33, flake8 skipsdist=True + [testenv] usedevelop=True commands = {envpython} tests/test.py - deps = -r{toxinidir}/requirements.txt + +[testenv:flake8] +commands = flake8 docker tests +deps = flake8 \ No newline at end of file