def test_substitute_run_args(container_handle, expected_name):
    class MockDocker(object):
        def _testdict(self, name):
            return {
                'Name': name,
                'NetworkSettings': {
                    'IPAddress': '172.17.42.1',
                    'Ports': {
                        '80': '8080',
                        '443': '4433',
                    }
                }
            }

        def inspect_image(self, image):
            return self._testdict(image)

        def inspect_container(self, container):
            return self._testdict(container)

    mock_dc = MockDocker()
    dc = DockerContainer(mock_dc, 'test')
    res = dc._substitute_run_args([
        "{{inspect['Name']}}" + container_handle,
        "{{inspect['NetworkSettings']['IPAddress']}}",
        "{{inspect['NetworkSettings']['Ports'].keys()}}"
    ])

    assert len(res) == 4
    assert res[0] == expected_name
    assert res[1] == '172.17.42.1'
    assert set(res[2:]) == set(['80', '443'])
 def test_backup_dont_overwrite(self, tmpdir, tarname):
     tmpdir.join(tarname).write('')
     configure_logger(test=True, verbosity=0)
     container = DockerContainer(self.cli, self.testcontainer)
     with pytest.raises(RuntimeError) as e:
         container.backup('/', str(tmpdir), 'backup')
         assert e.message.startswith('Backup failed')
    def test_container_get_image(self):
        container = DockerContainer(self.cli, self.testcontainer, {}, {},
                                    self.build_instructions())
        container.build_image()

        assert container.get_image(self.testimage)
        assert container.get_image('{}:latest'.format(self.testimage))
        assert container.get_image()
        assert not container.get_image('{}:othertag'.format(self.testimage))
        assert not container.get_image('non-existent')
def test_creation_manipulation():
    port_bindings = {22: 2222, 44: 4444}
    startup = {'port_bindings': port_bindings}
    ports = [22, 44]

    dc = DockerContainer(None, 'test', startup=startup)
    assert set(dc.creation['ports']) == set(ports)
Exemple #5
0
def test_output_filter_create_container(v, expected):
    configure_logger(test=True, verbosity=v)
    dc = DockerContainer(None, 'test')
    dc._log_output('', 'create_container')
    dc._log_output({'Id': 'abc', 'Warnings': None}, 'create_container')
    dc._log_output({'Id': 'def', 'Warnings': 'ohoh'}, 'create_container')

    infos = last_info_line(None)
    assert len(infos) == expected
    if len(infos) > 1:
        assert infos[0].endswith('Created image with Id abc')
        assert infos[1].endswith('Created image with Id def')
        assert infos[2].endswith('ohoh')
Exemple #6
0
def test_output_filter_build_image(v, expected):
    configure_logger(test=True, verbosity=v)
    dc = DockerContainer(None, 'test')
    dc._log_output('', 'build')
    dc._log_output('{"stream": "hello"}', 'build')
    dc._log_output('{"stream": "world"}', 'build')
    dc._log_output({"stream": "world"}, 'build')

    infos = last_info_line(None)
    assert len(infos) == expected
    if len(infos) > 1:
        assert infos[0].endswith('hello')
        assert infos[1].endswith('world')
def test_startup_manipulation(tmpdir):
    with tmpdir.as_cwd():
        os.mkdir(str(tmpdir.join('path')))
        bind_path_host = '${CONFIG_DIR}/path'
        bind_container = {'binds': 'path', 'ro': True}
        startup = {
            'other_key': 'other_value',
            'binds': {
                bind_path_host: bind_container
            },
        }
        build = {'path': str(tmpdir)}
        dc = DockerContainer(None, 'test', startup=startup, build=build)
        new_key_expected = str(tmpdir.join('path'))
        assert dc.startup['binds'].keys() == [new_key_expected]
        assert dc.startup['binds'][new_key_expected] == bind_container
        assert 'other_key' in dc.startup
        os.rmdir(str(tmpdir.join('path')))

    # It fails, if the bind directory does not exist...
    with pytest.raises(ValueError):
        dc = DockerContainer(None, 'test', startup=startup, build=build)
def test_execute_on_host():
    dc = DockerContainer(None, 'host')
    configure_logger(test=True, verbosity=1)
    with pytest.raises(RuntimeError) as e:
        res = dc.execute(['false'], shell=True)
        assert res > 0
        e.message.endswith('error code {}'.format(res))

    res = dc.execute(
        ['echo -n "hallo "; echo -n foo 1>&2; echo -n welt; echo -n bar 1>&2'],
        shell=True)
    assert res == 0
    assert last_info_line()[0].endswith('hallo welt')
    assert last_error_line()[0].endswith('foobar')

    res = dc.execute([
        'echo "hallo "; echo foo 1>&2; sleep 0.01;'
        'echo welt; echo bar 1>&2'
    ],
                     shell=True)
    assert res == 0
    assert last_info_line()[0].endswith(': welt')
    assert last_error_line()[0].endswith(': bar')
Exemple #9
0
def test_output_filter_pull(v, expected):
    configure_logger(test=True, verbosity=v)
    dc = DockerContainer(None, 'test')
    dc._log_output('', 'pull')
    # ignore lines without status
    dc._log_output('{"id": "ab", "progressDetail": 21}', 'pull')
    for i in range(41):
        dc._log_output(
            '{{"status": "a", "progressDetail": {{"{0}": 40}}, "id": "bc"}}'.
            format(i), 'pull')
    # different pull command
    dc._log_output('{"id": "cd", "status": "b", "progressDetail": 1}', 'pull')
    # invalid pull commands go through without an error
    dc._log_output({"Id": "cd", "Warnings": 1}, 'pull')
    dc._log_output('{"Id": "cd", "status": "invalid"}', 'pull')
    infos = last_info_line(None)
    assert len(infos) == expected
    if len(infos) > 1:
        assert infos[0].endswith('(bc) a: {}'.format(repr({u"0": 40})))
    def test_container_backup_restore(self, tmpdir):
        configure_logger(test=True, verbosity=1)
        container = DockerContainer(self.cli, self.testcontainer, {}, {},
                                    self.build_instructions())
        container.create()

        container.manipulate_volumes(command=['touch', '/data/empty_file'])

        container.manipulate_volumes(command=['ls', '/data/'])

        assert last_info_line(3)[0] == "empty_file"

        container.backup('/data', str(tmpdir), 'backup')

        assert os.path.exists(str(tmpdir.join('backup.tar.gz')))

        container.manipulate_volumes(command=['rm', '/data/empty_file'])

        container.manipulate_volumes(command=['ls', '/data/'])

        assert last_info_line(3)[0].endswith("Output follows")

        container.restore(str(tmpdir), 'backup')

        assert os.path.exists(str(tmpdir.join('backup.tar.gz')))

        container.manipulate_volumes(command=['ls', '/data/'])

        assert last_info_line(3)[0] == "empty_file"
 def test_container_non_existent(self):
     container = DockerContainer(self.cli, 'test', {})
     with pytest.raises(RuntimeError):
         container.start()
    def test_container_creation(self):
        creation = {'image': self.testimage}
        container = DockerContainer(self.cli, self.testcontainer, creation)
        with pytest.raises(RuntimeError):
            container.start()

        assert str(container) == "No id yet"

        build_instructions = {
            'fileobj': BytesIO(test_dockerfile.encode('utf-8')),
            'rm': True,
            'tag': self.testimage,
        }

        container = DockerContainer(self.cli, self.testcontainer, {}, {},
                                    build_instructions)
        container.start()

        container.start()
        time.sleep(0.01)
        assert container.is_started()

        assert str(container)

        # delete container and it should work again afterwards...

        container.stop(timeout=0)
        container.remove(v=True)

        assert not container.get_container()
        container.start()

        assert container.get_container()

        # make sure, that containers with subset of the name are not found
        sub_name_container = DockerContainer(self.cli,
                                             self.testcontainer[2:-2])
        assert not sub_name_container.get_container()

        container.start(restart=True, timeout=0)
        time.sleep(0.01)
        assert container.is_started()