set engine version for unit tests to avoid querying the engine

Signed-off-by: aiordache <anca.iordache@docker.com>
This commit is contained in:
aiordache 2020-08-20 14:59:36 +02:00
parent 727080b3cc
commit c7c5b551fc
7 changed files with 71 additions and 47 deletions

View File

@ -8,10 +8,10 @@ import six
import websocket import websocket
from .. import auth from .. import auth
from ..constants import (DEFAULT_DOCKER_API_VERSION, DEFAULT_NUM_POOLS, from ..constants import (DEFAULT_NUM_POOLS, DEFAULT_NUM_POOLS_SSH,
DEFAULT_NUM_POOLS_SSH, DEFAULT_TIMEOUT_SECONDS, DEFAULT_TIMEOUT_SECONDS, DEFAULT_USER_AGENT,
DEFAULT_USER_AGENT, IS_WINDOWS_PLATFORM, IS_WINDOWS_PLATFORM, MINIMUM_DOCKER_API_VERSION,
MINIMUM_DOCKER_API_VERSION, STREAM_HEADER_SIZE_BYTES) STREAM_HEADER_SIZE_BYTES)
from ..errors import (DockerException, InvalidVersion, TLSParameterError, from ..errors import (DockerException, InvalidVersion, TLSParameterError,
create_api_error_from_http_exception) create_api_error_from_http_exception)
from ..tls import TLSConfig from ..tls import TLSConfig
@ -181,13 +181,13 @@ class APIClient(
self.base_url = base_url self.base_url = base_url
# version detection needs to be after unix adapter mounting # version detection needs to be after unix adapter mounting
if version is None or ( if version is None or (isinstance(
isinstance(version, six.string_types) and version,
version.lower()) == 'auto': six.string_types
) and version.lower() == 'auto'):
self._version = self._retrieve_server_version() self._version = self._retrieve_server_version()
else: else:
self._version = version self._version = version
if not isinstance(self._version, six.string_types): if not isinstance(self._version, six.string_types):
raise DockerException( raise DockerException(
'Version parameter must be a string or None. Found {0}'.format( 'Version parameter must be a string or None. Found {0}'.format(

View File

@ -62,7 +62,7 @@ class DockerClient(object):
Args: Args:
version (str): The version of the API to use. Set to ``auto`` to version (str): The version of the API to use. Set to ``auto`` to
automatically detect the server's version. Default: ``1.35`` automatically detect the server's version. Default: ``auto``
timeout (int): Default timeout for API calls, in seconds. timeout (int): Default timeout for API calls, in seconds.
ssl_version (int): A valid `SSL version`_. ssl_version (int): A valid `SSL version`_.
assert_hostname (bool): Verify the hostname of the server. assert_hostname (bool): Verify the hostname of the server.

View File

@ -1,26 +1,26 @@
import datetime import datetime
import json
import io import io
import json
import os import os
import re import re
import shutil import shutil
import socket import socket
import struct
import tempfile import tempfile
import threading import threading
import time import time
import unittest import unittest
import docker import docker
from docker.api import APIClient import pytest
import requests import requests
from requests.packages import urllib3
import six import six
import struct from docker.api import APIClient
from docker.constants import DEFAULT_DOCKER_API_VERSION
from requests.packages import urllib3
from . import fake_api from . import fake_api
import pytest
try: try:
from unittest import mock from unittest import mock
except ImportError: except ImportError:
@ -105,7 +105,7 @@ class BaseAPIClientTest(unittest.TestCase):
_read_from_socket=fake_read_from_socket _read_from_socket=fake_read_from_socket
) )
self.patcher.start() self.patcher.start()
self.client = APIClient() self.client = APIClient(version=DEFAULT_DOCKER_API_VERSION)
def tearDown(self): def tearDown(self):
self.client.close() self.client.close()
@ -282,27 +282,37 @@ class DockerApiTest(BaseAPIClientTest):
return socket_adapter.socket_path return socket_adapter.socket_path
def test_url_compatibility_unix(self): def test_url_compatibility_unix(self):
c = APIClient(base_url="unix://socket") c = APIClient(
base_url="unix://socket",
version=DEFAULT_DOCKER_API_VERSION)
assert self._socket_path_for_client_session(c) == '/socket' assert self._socket_path_for_client_session(c) == '/socket'
def test_url_compatibility_unix_triple_slash(self): def test_url_compatibility_unix_triple_slash(self):
c = APIClient(base_url="unix:///socket") c = APIClient(
base_url="unix:///socket",
version=DEFAULT_DOCKER_API_VERSION)
assert self._socket_path_for_client_session(c) == '/socket' assert self._socket_path_for_client_session(c) == '/socket'
def test_url_compatibility_http_unix_triple_slash(self): def test_url_compatibility_http_unix_triple_slash(self):
c = APIClient(base_url="http+unix:///socket") c = APIClient(
base_url="http+unix:///socket",
version=DEFAULT_DOCKER_API_VERSION)
assert self._socket_path_for_client_session(c) == '/socket' assert self._socket_path_for_client_session(c) == '/socket'
def test_url_compatibility_http(self): def test_url_compatibility_http(self):
c = APIClient(base_url="http://hostname:1234") c = APIClient(
base_url="http://hostname:1234",
version=DEFAULT_DOCKER_API_VERSION)
assert c.base_url == "http://hostname:1234" assert c.base_url == "http://hostname:1234"
def test_url_compatibility_tcp(self): def test_url_compatibility_tcp(self):
c = APIClient(base_url="tcp://hostname:1234") c = APIClient(
base_url="tcp://hostname:1234",
version=DEFAULT_DOCKER_API_VERSION)
assert c.base_url == "http://hostname:1234" assert c.base_url == "http://hostname:1234"
@ -447,7 +457,9 @@ class UnixSocketStreamTest(unittest.TestCase):
b'\r\n' b'\r\n'
) + b'\r\n'.join(lines) ) + b'\r\n'.join(lines)
with APIClient(base_url="http+unix://" + self.socket_file) as client: with APIClient(
base_url="http+unix://" + self.socket_file,
version=DEFAULT_DOCKER_API_VERSION) as client:
for i in range(5): for i in range(5):
try: try:
stream = client.build( stream = client.build(
@ -532,7 +544,10 @@ class TCPSocketStreamTest(unittest.TestCase):
def request(self, stream=None, tty=None, demux=None): def request(self, stream=None, tty=None, demux=None):
assert stream is not None and tty is not None and demux is not None assert stream is not None and tty is not None and demux is not None
with APIClient(base_url=self.address) as client: with APIClient(
base_url=self.address,
version=DEFAULT_DOCKER_API_VERSION
) as client:
if tty: if tty:
url = client._url('/tty') url = client._url('/tty')
else: else:
@ -597,7 +612,7 @@ class UserAgentTest(unittest.TestCase):
self.patcher.stop() self.patcher.stop()
def test_default_user_agent(self): def test_default_user_agent(self):
client = APIClient() client = APIClient(version=DEFAULT_DOCKER_API_VERSION)
client.version() client.version()
assert self.mock_send.call_count == 1 assert self.mock_send.call_count == 1
@ -606,7 +621,9 @@ class UserAgentTest(unittest.TestCase):
assert headers['User-Agent'] == expected assert headers['User-Agent'] == expected
def test_custom_user_agent(self): def test_custom_user_agent(self):
client = APIClient(user_agent='foo/bar') client = APIClient(
user_agent='foo/bar',
version=DEFAULT_DOCKER_API_VERSION)
client.version() client.version()
assert self.mock_send.call_count == 1 assert self.mock_send.call_count == 1
@ -626,7 +643,7 @@ class DisableSocketTest(unittest.TestCase):
return self.timeout return self.timeout
def setUp(self): def setUp(self):
self.client = APIClient() self.client = APIClient(version=DEFAULT_DOCKER_API_VERSION)
def test_disable_socket_timeout(self): def test_disable_socket_timeout(self):
"""Test that the timeout is disabled on a generic socket object.""" """Test that the timeout is disabled on a generic socket object."""

View File

@ -1,14 +1,14 @@
import datetime import datetime
import docker
from docker.utils import kwargs_from_env
from docker.constants import (
DEFAULT_DOCKER_API_VERSION, DEFAULT_TIMEOUT_SECONDS
)
import os import os
import unittest import unittest
from . import fake_api import docker
import pytest import pytest
from docker.constants import (
DEFAULT_DOCKER_API_VERSION, DEFAULT_TIMEOUT_SECONDS)
from docker.utils import kwargs_from_env
from . import fake_api
try: try:
from unittest import mock from unittest import mock
@ -25,33 +25,33 @@ class ClientTest(unittest.TestCase):
def test_events(self, mock_func): def test_events(self, mock_func):
since = datetime.datetime(2016, 1, 1, 0, 0) since = datetime.datetime(2016, 1, 1, 0, 0)
mock_func.return_value = fake_api.get_fake_events()[1] mock_func.return_value = fake_api.get_fake_events()[1]
client = docker.from_env() client = docker.from_env(version=DEFAULT_DOCKER_API_VERSION)
assert client.events(since=since) == mock_func.return_value assert client.events(since=since) == mock_func.return_value
mock_func.assert_called_with(since=since) mock_func.assert_called_with(since=since)
@mock.patch('docker.api.APIClient.info') @mock.patch('docker.api.APIClient.info')
def test_info(self, mock_func): def test_info(self, mock_func):
mock_func.return_value = fake_api.get_fake_info()[1] mock_func.return_value = fake_api.get_fake_info()[1]
client = docker.from_env() client = docker.from_env(version=DEFAULT_DOCKER_API_VERSION)
assert client.info() == mock_func.return_value assert client.info() == mock_func.return_value
mock_func.assert_called_with() mock_func.assert_called_with()
@mock.patch('docker.api.APIClient.ping') @mock.patch('docker.api.APIClient.ping')
def test_ping(self, mock_func): def test_ping(self, mock_func):
mock_func.return_value = True mock_func.return_value = True
client = docker.from_env() client = docker.from_env(version=DEFAULT_DOCKER_API_VERSION)
assert client.ping() is True assert client.ping() is True
mock_func.assert_called_with() mock_func.assert_called_with()
@mock.patch('docker.api.APIClient.version') @mock.patch('docker.api.APIClient.version')
def test_version(self, mock_func): def test_version(self, mock_func):
mock_func.return_value = fake_api.get_fake_version()[1] mock_func.return_value = fake_api.get_fake_version()[1]
client = docker.from_env() client = docker.from_env(version=DEFAULT_DOCKER_API_VERSION)
assert client.version() == mock_func.return_value assert client.version() == mock_func.return_value
mock_func.assert_called_with() mock_func.assert_called_with()
def test_call_api_client_method(self): def test_call_api_client_method(self):
client = docker.from_env() client = docker.from_env(version=DEFAULT_DOCKER_API_VERSION)
with pytest.raises(AttributeError) as cm: with pytest.raises(AttributeError) as cm:
client.create_container() client.create_container()
s = cm.exconly() s = cm.exconly()
@ -65,7 +65,9 @@ class ClientTest(unittest.TestCase):
assert "this method is now on the object APIClient" not in s assert "this method is now on the object APIClient" not in s
def test_call_containers(self): def test_call_containers(self):
client = docker.DockerClient(**kwargs_from_env()) client = docker.DockerClient(
version=DEFAULT_DOCKER_API_VERSION,
**kwargs_from_env())
with pytest.raises(TypeError) as cm: with pytest.raises(TypeError) as cm:
client.containers() client.containers()
@ -90,7 +92,7 @@ class FromEnvTest(unittest.TestCase):
os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376', os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376',
DOCKER_CERT_PATH=TEST_CERT_DIR, DOCKER_CERT_PATH=TEST_CERT_DIR,
DOCKER_TLS_VERIFY='1') DOCKER_TLS_VERIFY='1')
client = docker.from_env() client = docker.from_env(version=DEFAULT_DOCKER_API_VERSION)
assert client.api.base_url == "https://192.168.59.103:2376" assert client.api.base_url == "https://192.168.59.103:2376"
def test_from_env_with_version(self): def test_from_env_with_version(self):
@ -102,11 +104,11 @@ class FromEnvTest(unittest.TestCase):
assert client.api._version == '2.32' assert client.api._version == '2.32'
def test_from_env_without_version_uses_default(self): def test_from_env_without_version_uses_default(self):
client = docker.from_env() client = docker.from_env(version=DEFAULT_DOCKER_API_VERSION)
assert client.api._version == DEFAULT_DOCKER_API_VERSION assert client.api._version == DEFAULT_DOCKER_API_VERSION
def test_from_env_without_timeout_uses_default(self): def test_from_env_without_timeout_uses_default(self):
client = docker.from_env() client = docker.from_env(version=DEFAULT_DOCKER_API_VERSION)
assert client.api.timeout == DEFAULT_TIMEOUT_SECONDS assert client.api.timeout == DEFAULT_TIMEOUT_SECONDS

View File

@ -1,6 +1,7 @@
from . import fake_stat
from docker import constants from docker import constants
from . import fake_stat
CURRENT_VERSION = 'v{0}'.format(constants.DEFAULT_DOCKER_API_VERSION) CURRENT_VERSION = 'v{0}'.format(constants.DEFAULT_DOCKER_API_VERSION)
FAKE_CONTAINER_ID = '3cc2351ab11b' FAKE_CONTAINER_ID = '3cc2351ab11b'

View File

@ -1,6 +1,7 @@
import copy import copy
import docker
import docker
from docker.constants import DEFAULT_DOCKER_API_VERSION
from . import fake_api from . import fake_api
try: try:
@ -30,7 +31,7 @@ def make_fake_api_client(overrides=None):
if overrides is None: if overrides is None:
overrides = {} overrides = {}
api_client = docker.APIClient() api_client = docker.APIClient(version=DEFAULT_DOCKER_API_VERSION)
mock_attrs = { mock_attrs = {
'build.return_value': fake_api.FAKE_IMAGE_ID, 'build.return_value': fake_api.FAKE_IMAGE_ID,
'commit.return_value': fake_api.post_fake_commit()[1], 'commit.return_value': fake_api.post_fake_commit()[1],
@ -50,6 +51,7 @@ def make_fake_api_client(overrides=None):
'networks.return_value': fake_api.get_fake_network_list()[1], 'networks.return_value': fake_api.get_fake_network_list()[1],
'start.return_value': None, 'start.return_value': None,
'wait.return_value': {'StatusCode': 0}, 'wait.return_value': {'StatusCode': 0},
'version.return_value': fake_api.get_fake_version()
} }
mock_attrs.update(overrides) mock_attrs.update(overrides)
mock_client = CopyReturnMagicMock(**mock_attrs) mock_client = CopyReturnMagicMock(**mock_attrs)
@ -62,6 +64,6 @@ def make_fake_client(overrides=None):
""" """
Returns a Client with a fake APIClient. Returns a Client with a fake APIClient.
""" """
client = docker.DockerClient() client = docker.DockerClient(version=DEFAULT_DOCKER_API_VERSION)
client.api = make_fake_api_client(overrides) client.api = make_fake_api_client(overrides)
return client return client

View File

@ -11,7 +11,7 @@ import unittest
import pytest import pytest
import six import six
from docker.api.client import APIClient from docker.api.client import APIClient
from docker.constants import IS_WINDOWS_PLATFORM from docker.constants import IS_WINDOWS_PLATFORM, DEFAULT_DOCKER_API_VERSION
from docker.errors import DockerException from docker.errors import DockerException
from docker.utils import (convert_filters, convert_volume_binds, from docker.utils import (convert_filters, convert_volume_binds,
decode_json_header, kwargs_from_env, parse_bytes, decode_json_header, kwargs_from_env, parse_bytes,
@ -35,7 +35,7 @@ class DecoratorsTest(unittest.TestCase):
def f(self, headers=None): def f(self, headers=None):
return headers return headers
client = APIClient() client = APIClient(version=DEFAULT_DOCKER_API_VERSION)
client._general_configs = {} client._general_configs = {}
g = update_headers(f) g = update_headers(f)
@ -86,6 +86,7 @@ class KwargsFromEnvTest(unittest.TestCase):
assert kwargs['tls'].verify assert kwargs['tls'].verify
parsed_host = parse_host(kwargs['base_url'], IS_WINDOWS_PLATFORM, True) parsed_host = parse_host(kwargs['base_url'], IS_WINDOWS_PLATFORM, True)
kwargs['version'] = DEFAULT_DOCKER_API_VERSION
try: try:
client = APIClient(**kwargs) client = APIClient(**kwargs)
assert parsed_host == client.base_url assert parsed_host == client.base_url
@ -106,6 +107,7 @@ class KwargsFromEnvTest(unittest.TestCase):
assert kwargs['tls'].assert_hostname is True assert kwargs['tls'].assert_hostname is True
assert kwargs['tls'].verify is False assert kwargs['tls'].verify is False
parsed_host = parse_host(kwargs['base_url'], IS_WINDOWS_PLATFORM, True) parsed_host = parse_host(kwargs['base_url'], IS_WINDOWS_PLATFORM, True)
kwargs['version'] = DEFAULT_DOCKER_API_VERSION
try: try:
client = APIClient(**kwargs) client = APIClient(**kwargs)
assert parsed_host == client.base_url assert parsed_host == client.base_url