12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157 |
- from __future__ import print_function
- import os
- import shutil
- import tempfile
- from operator import itemgetter
- from .. import mock
- from .. import unittest
- from compose.config import config
- from compose.config.errors import ConfigurationError
- def make_service_dict(name, service_dict, working_dir, filename=None):
- """
- Test helper function to construct a ServiceLoader
- """
- return config.ServiceLoader(
- working_dir=working_dir,
- filename=filename,
- service_name=name,
- service_dict=service_dict).make_service_dict()
- def service_sort(services):
- return sorted(services, key=itemgetter('name'))
- class ConfigTest(unittest.TestCase):
- def test_load(self):
- service_dicts = config.load(
- config.ConfigDetails(
- {
- 'foo': {'image': 'busybox'},
- 'bar': {'image': 'busybox', 'environment': ['FOO=1']},
- },
- 'tests/fixtures/extends',
- 'common.yml'
- )
- )
- self.assertEqual(
- service_sort(service_dicts),
- service_sort([
- {
- 'name': 'bar',
- 'image': 'busybox',
- 'environment': {'FOO': '1'},
- },
- {
- 'name': 'foo',
- 'image': 'busybox',
- }
- ])
- )
- def test_load_throws_error_when_not_dict(self):
- with self.assertRaises(ConfigurationError):
- config.load(
- config.ConfigDetails(
- {'web': 'busybox:latest'},
- 'working_dir',
- 'filename.yml'
- )
- )
- def test_config_invalid_service_names(self):
- with self.assertRaises(ConfigurationError):
- for invalid_name in ['?not?allowed', ' ', '', '!', '/', '\xe2']:
- config.load(
- config.ConfigDetails(
- {invalid_name: {'image': 'busybox'}},
- 'working_dir',
- 'filename.yml'
- )
- )
- def test_config_integer_service_name_raise_validation_error(self):
- expected_error_msg = "Service name: 1 needs to be a string, eg '1'"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {1: {'image': 'busybox'}},
- 'working_dir',
- 'filename.yml'
- )
- )
- def test_config_valid_service_names(self):
- for valid_name in ['_', '-', '.__.', '_what-up.', 'what_.up----', 'whatup']:
- config.load(
- config.ConfigDetails(
- {valid_name: {'image': 'busybox'}},
- 'tests/fixtures/extends',
- 'common.yml'
- )
- )
- def test_config_invalid_ports_format_validation(self):
- expected_error_msg = "Service 'web' configuration key 'ports' contains an invalid type"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- for invalid_ports in [{"1": "8000"}, False, 0, "8000", 8000, ["8000", "8000"]]:
- config.load(
- config.ConfigDetails(
- {'web': {'image': 'busybox', 'ports': invalid_ports}},
- 'working_dir',
- 'filename.yml'
- )
- )
- def test_config_valid_ports_format_validation(self):
- valid_ports = [["8000", "9000"], ["8000/8050"], ["8000"], [8000], ["49153-49154:3002-3003"]]
- for ports in valid_ports:
- config.load(
- config.ConfigDetails(
- {'web': {'image': 'busybox', 'ports': ports}},
- 'working_dir',
- 'filename.yml'
- )
- )
- def test_config_hint(self):
- expected_error_msg = "(did you mean 'privileged'?)"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {
- 'foo': {'image': 'busybox', 'privilige': 'something'},
- },
- 'tests/fixtures/extends',
- 'filename.yml'
- )
- )
- def test_invalid_config_build_and_image_specified(self):
- expected_error_msg = "Service 'foo' has both an image and build path specified."
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {
- 'foo': {'image': 'busybox', 'build': '.'},
- },
- 'tests/fixtures/extends',
- 'filename.yml'
- )
- )
- def test_invalid_config_type_should_be_an_array(self):
- expected_error_msg = "Service 'foo' configuration key 'links' contains an invalid type, it should be an array"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {
- 'foo': {'image': 'busybox', 'links': 'an_link'},
- },
- 'tests/fixtures/extends',
- 'filename.yml'
- )
- )
- def test_invalid_config_not_a_dictionary(self):
- expected_error_msg = "Top level object needs to be a dictionary."
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- ['foo', 'lol'],
- 'tests/fixtures/extends',
- 'filename.yml'
- )
- )
- def test_invalid_config_not_unique_items(self):
- expected_error_msg = "has non-unique elements"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {
- 'web': {'build': '.', 'devices': ['/dev/foo:/dev/foo', '/dev/foo:/dev/foo']}
- },
- 'tests/fixtures/extends',
- 'filename.yml'
- )
- )
- def test_invalid_list_of_strings_format(self):
- expected_error_msg = "'command' contains an invalid type, valid types are string or array"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {
- 'web': {'build': '.', 'command': [1]}
- },
- 'tests/fixtures/extends',
- 'filename.yml'
- )
- )
- def test_config_image_and_dockerfile_raise_validation_error(self):
- expected_error_msg = "Service 'web' has both an image and alternate Dockerfile."
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {'web': {'image': 'busybox', 'dockerfile': 'Dockerfile.alt'}},
- 'working_dir',
- 'filename.yml'
- )
- )
- def test_config_extra_hosts_string_raises_validation_error(self):
- expected_error_msg = "Service 'web' configuration key 'extra_hosts' contains an invalid type"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {'web': {
- 'image': 'busybox',
- 'extra_hosts': 'somehost:162.242.195.82'
- }},
- 'working_dir',
- 'filename.yml'
- )
- )
- def test_config_extra_hosts_list_of_dicts_validation_error(self):
- expected_error_msg = "Service 'web' configuration key 'extra_hosts' contains an invalid type"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {'web': {
- 'image': 'busybox',
- 'extra_hosts': [
- {'somehost': '162.242.195.82'},
- {'otherhost': '50.31.209.229'}
- ]
- }},
- 'working_dir',
- 'filename.yml'
- )
- )
- def test_valid_config_which_allows_two_type_definitions(self):
- expose_values = [["8000"], [8000]]
- for expose in expose_values:
- service = config.load(
- config.ConfigDetails(
- {'web': {
- 'image': 'busybox',
- 'expose': expose
- }},
- 'working_dir',
- 'filename.yml'
- )
- )
- self.assertEqual(service[0]['expose'], expose)
- def test_valid_config_oneof_string_or_list(self):
- entrypoint_values = [["sh"], "sh"]
- for entrypoint in entrypoint_values:
- service = config.load(
- config.ConfigDetails(
- {'web': {
- 'image': 'busybox',
- 'entrypoint': entrypoint
- }},
- 'working_dir',
- 'filename.yml'
- )
- )
- self.assertEqual(service[0]['entrypoint'], entrypoint)
- def test_validation_message_for_invalid_type_when_multiple_types_allowed(self):
- expected_error_msg = "Service 'web' configuration key 'mem_limit' contains an invalid type, it should be a number or a string"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {'web': {
- 'image': 'busybox',
- 'mem_limit': ['incorrect']
- }},
- 'working_dir',
- 'filename.yml'
- )
- )
- class InterpolationTest(unittest.TestCase):
- @mock.patch.dict(os.environ)
- def test_config_file_with_environment_variable(self):
- os.environ.update(
- IMAGE="busybox",
- HOST_PORT="80",
- LABEL_VALUE="myvalue",
- )
- service_dicts = config.load(
- config.find('tests/fixtures/environment-interpolation', None),
- )
- self.assertEqual(service_dicts, [
- {
- 'name': 'web',
- 'image': 'busybox',
- 'ports': ['80:8000'],
- 'labels': {'mylabel': 'myvalue'},
- 'hostname': 'host-',
- 'command': '${ESCAPED}',
- }
- ])
- @mock.patch.dict(os.environ)
- def test_unset_variable_produces_warning(self):
- os.environ.pop('FOO', None)
- os.environ.pop('BAR', None)
- config_details = config.ConfigDetails(
- config={
- 'web': {
- 'image': '${FOO}',
- 'command': '${BAR}',
- 'container_name': '${BAR}',
- },
- },
- working_dir='.',
- filename=None,
- )
- with mock.patch('compose.config.interpolation.log') as log:
- config.load(config_details)
- self.assertEqual(2, log.warn.call_count)
- warnings = sorted(args[0][0] for args in log.warn.call_args_list)
- self.assertIn('BAR', warnings[0])
- self.assertIn('FOO', warnings[1])
- @mock.patch.dict(os.environ)
- def test_invalid_interpolation(self):
- with self.assertRaises(config.ConfigurationError) as cm:
- config.load(
- config.ConfigDetails(
- {'web': {'image': '${'}},
- 'working_dir',
- 'filename.yml'
- )
- )
- self.assertIn('Invalid', cm.exception.msg)
- self.assertIn('for "image" option', cm.exception.msg)
- self.assertIn('in service "web"', cm.exception.msg)
- self.assertIn('"${"', cm.exception.msg)
- @mock.patch.dict(os.environ)
- def test_volume_binding_with_environment_variable(self):
- os.environ['VOLUME_PATH'] = '/host/path'
- d = config.load(
- config.ConfigDetails(
- config={'foo': {'build': '.', 'volumes': ['${VOLUME_PATH}:/container/path']}},
- working_dir='.',
- filename=None,
- )
- )[0]
- self.assertEqual(d['volumes'], ['/host/path:/container/path'])
- @mock.patch.dict(os.environ)
- def test_volume_binding_with_home(self):
- os.environ['HOME'] = '/home/user'
- d = make_service_dict('foo', {'build': '.', 'volumes': ['~:/container/path']}, working_dir='.')
- self.assertEqual(d['volumes'], ['/home/user:/container/path'])
- @mock.patch.dict(os.environ)
- def test_volume_binding_with_local_dir_name_raises_warning(self):
- def make_dict(**config):
- config['build'] = '.'
- make_service_dict('foo', config, working_dir='.')
- with mock.patch('compose.config.config.log.warn') as warn:
- make_dict(volumes=['/container/path'])
- self.assertEqual(0, warn.call_count)
- make_dict(volumes=['/data:/container/path'])
- self.assertEqual(0, warn.call_count)
- make_dict(volumes=['.:/container/path'])
- self.assertEqual(0, warn.call_count)
- make_dict(volumes=['..:/container/path'])
- self.assertEqual(0, warn.call_count)
- make_dict(volumes=['./data:/container/path'])
- self.assertEqual(0, warn.call_count)
- make_dict(volumes=['../data:/container/path'])
- self.assertEqual(0, warn.call_count)
- make_dict(volumes=['.profile:/container/path'])
- self.assertEqual(0, warn.call_count)
- make_dict(volumes=['~:/container/path'])
- self.assertEqual(0, warn.call_count)
- make_dict(volumes=['~/data:/container/path'])
- self.assertEqual(0, warn.call_count)
- make_dict(volumes=['~tmp:/container/path'])
- self.assertEqual(0, warn.call_count)
- make_dict(volumes=['data:/container/path'], volume_driver='mydriver')
- self.assertEqual(0, warn.call_count)
- make_dict(volumes=['data:/container/path'])
- self.assertEqual(1, warn.call_count)
- warning = warn.call_args[0][0]
- self.assertIn('"data:/container/path"', warning)
- self.assertIn('"./data:/container/path"', warning)
- def test_named_volume_with_driver_does_not_expand(self):
- d = make_service_dict('foo', {
- 'build': '.',
- 'volumes': ['namedvolume:/data'],
- 'volume_driver': 'foodriver',
- }, working_dir='.')
- self.assertEqual(d['volumes'], ['namedvolume:/data'])
- @mock.patch.dict(os.environ)
- def test_home_directory_with_driver_does_not_expand(self):
- os.environ['NAME'] = 'surprise!'
- d = make_service_dict('foo', {
- 'build': '.',
- 'volumes': ['~:/data'],
- 'volume_driver': 'foodriver',
- }, working_dir='.')
- self.assertEqual(d['volumes'], ['~:/data'])
- class MergePathMappingTest(object):
- def config_name(self):
- return ""
- def test_empty(self):
- service_dict = config.merge_service_dicts({}, {})
- self.assertNotIn(self.config_name(), service_dict)
- def test_no_override(self):
- service_dict = config.merge_service_dicts(
- {self.config_name(): ['/foo:/code', '/data']},
- {},
- )
- self.assertEqual(set(service_dict[self.config_name()]), set(['/foo:/code', '/data']))
- def test_no_base(self):
- service_dict = config.merge_service_dicts(
- {},
- {self.config_name(): ['/bar:/code']},
- )
- self.assertEqual(set(service_dict[self.config_name()]), set(['/bar:/code']))
- def test_override_explicit_path(self):
- service_dict = config.merge_service_dicts(
- {self.config_name(): ['/foo:/code', '/data']},
- {self.config_name(): ['/bar:/code']},
- )
- self.assertEqual(set(service_dict[self.config_name()]), set(['/bar:/code', '/data']))
- def test_add_explicit_path(self):
- service_dict = config.merge_service_dicts(
- {self.config_name(): ['/foo:/code', '/data']},
- {self.config_name(): ['/bar:/code', '/quux:/data']},
- )
- self.assertEqual(set(service_dict[self.config_name()]), set(['/bar:/code', '/quux:/data']))
- def test_remove_explicit_path(self):
- service_dict = config.merge_service_dicts(
- {self.config_name(): ['/foo:/code', '/quux:/data']},
- {self.config_name(): ['/bar:/code', '/data']},
- )
- self.assertEqual(set(service_dict[self.config_name()]), set(['/bar:/code', '/data']))
- class MergeVolumesTest(unittest.TestCase, MergePathMappingTest):
- def config_name(self):
- return 'volumes'
- class MergeDevicesTest(unittest.TestCase, MergePathMappingTest):
- def config_name(self):
- return 'devices'
- class BuildOrImageMergeTest(unittest.TestCase):
- def test_merge_build_or_image_no_override(self):
- self.assertEqual(
- config.merge_service_dicts({'build': '.'}, {}),
- {'build': '.'},
- )
- self.assertEqual(
- config.merge_service_dicts({'image': 'redis'}, {}),
- {'image': 'redis'},
- )
- def test_merge_build_or_image_override_with_same(self):
- self.assertEqual(
- config.merge_service_dicts({'build': '.'}, {'build': './web'}),
- {'build': './web'},
- )
- self.assertEqual(
- config.merge_service_dicts({'image': 'redis'}, {'image': 'postgres'}),
- {'image': 'postgres'},
- )
- def test_merge_build_or_image_override_with_other(self):
- self.assertEqual(
- config.merge_service_dicts({'build': '.'}, {'image': 'redis'}),
- {'image': 'redis'}
- )
- self.assertEqual(
- config.merge_service_dicts({'image': 'redis'}, {'build': '.'}),
- {'build': '.'}
- )
- class MergeListsTest(unittest.TestCase):
- def test_empty(self):
- service_dict = config.merge_service_dicts({}, {})
- self.assertNotIn('ports', service_dict)
- def test_no_override(self):
- service_dict = config.merge_service_dicts(
- {'ports': ['10:8000', '9000']},
- {},
- )
- self.assertEqual(set(service_dict['ports']), set(['10:8000', '9000']))
- def test_no_base(self):
- service_dict = config.merge_service_dicts(
- {},
- {'ports': ['10:8000', '9000']},
- )
- self.assertEqual(set(service_dict['ports']), set(['10:8000', '9000']))
- def test_add_item(self):
- service_dict = config.merge_service_dicts(
- {'ports': ['10:8000', '9000']},
- {'ports': ['20:8000']},
- )
- self.assertEqual(set(service_dict['ports']), set(['10:8000', '9000', '20:8000']))
- class MergeStringsOrListsTest(unittest.TestCase):
- def test_no_override(self):
- service_dict = config.merge_service_dicts(
- {'dns': '8.8.8.8'},
- {},
- )
- self.assertEqual(set(service_dict['dns']), set(['8.8.8.8']))
- def test_no_base(self):
- service_dict = config.merge_service_dicts(
- {},
- {'dns': '8.8.8.8'},
- )
- self.assertEqual(set(service_dict['dns']), set(['8.8.8.8']))
- def test_add_string(self):
- service_dict = config.merge_service_dicts(
- {'dns': ['8.8.8.8']},
- {'dns': '9.9.9.9'},
- )
- self.assertEqual(set(service_dict['dns']), set(['8.8.8.8', '9.9.9.9']))
- def test_add_list(self):
- service_dict = config.merge_service_dicts(
- {'dns': '8.8.8.8'},
- {'dns': ['9.9.9.9']},
- )
- self.assertEqual(set(service_dict['dns']), set(['8.8.8.8', '9.9.9.9']))
- class MergeLabelsTest(unittest.TestCase):
- def test_empty(self):
- service_dict = config.merge_service_dicts({}, {})
- self.assertNotIn('labels', service_dict)
- def test_no_override(self):
- service_dict = config.merge_service_dicts(
- make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
- make_service_dict('foo', {'build': '.'}, 'tests/'),
- )
- self.assertEqual(service_dict['labels'], {'foo': '1', 'bar': ''})
- def test_no_base(self):
- service_dict = config.merge_service_dicts(
- make_service_dict('foo', {'build': '.'}, 'tests/'),
- make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
- )
- self.assertEqual(service_dict['labels'], {'foo': '2'})
- def test_override_explicit_value(self):
- service_dict = config.merge_service_dicts(
- make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
- make_service_dict('foo', {'build': '.', 'labels': ['foo=2']}, 'tests/'),
- )
- self.assertEqual(service_dict['labels'], {'foo': '2', 'bar': ''})
- def test_add_explicit_value(self):
- service_dict = config.merge_service_dicts(
- make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar']}, 'tests/'),
- make_service_dict('foo', {'build': '.', 'labels': ['bar=2']}, 'tests/'),
- )
- self.assertEqual(service_dict['labels'], {'foo': '1', 'bar': '2'})
- def test_remove_explicit_value(self):
- service_dict = config.merge_service_dicts(
- make_service_dict('foo', {'build': '.', 'labels': ['foo=1', 'bar=2']}, 'tests/'),
- make_service_dict('foo', {'build': '.', 'labels': ['bar']}, 'tests/'),
- )
- self.assertEqual(service_dict['labels'], {'foo': '1', 'bar': ''})
- class MemoryOptionsTest(unittest.TestCase):
- def test_validation_fails_with_just_memswap_limit(self):
- """
- When you set a 'memswap_limit' it is invalid config unless you also set
- a mem_limit
- """
- expected_error_msg = (
- "Invalid 'memswap_limit' configuration for 'foo' service: when "
- "defining 'memswap_limit' you must set 'mem_limit' as well"
- )
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {
- 'foo': {'image': 'busybox', 'memswap_limit': 2000000},
- },
- 'tests/fixtures/extends',
- 'filename.yml'
- )
- )
- def test_validation_with_correct_memswap_values(self):
- service_dict = config.load(
- config.ConfigDetails(
- {'foo': {'image': 'busybox', 'mem_limit': 1000000, 'memswap_limit': 2000000}},
- 'tests/fixtures/extends',
- 'common.yml'
- )
- )
- self.assertEqual(service_dict[0]['memswap_limit'], 2000000)
- def test_memswap_can_be_a_string(self):
- service_dict = config.load(
- config.ConfigDetails(
- {'foo': {'image': 'busybox', 'mem_limit': "1G", 'memswap_limit': "512M"}},
- 'tests/fixtures/extends',
- 'common.yml'
- )
- )
- self.assertEqual(service_dict[0]['memswap_limit'], "512M")
- class EnvTest(unittest.TestCase):
- def test_parse_environment_as_list(self):
- environment = [
- 'NORMAL=F1',
- 'CONTAINS_EQUALS=F=2',
- 'TRAILING_EQUALS=',
- ]
- self.assertEqual(
- config.parse_environment(environment),
- {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''},
- )
- def test_parse_environment_as_dict(self):
- environment = {
- 'NORMAL': 'F1',
- 'CONTAINS_EQUALS': 'F=2',
- 'TRAILING_EQUALS': None,
- }
- self.assertEqual(config.parse_environment(environment), environment)
- def test_parse_environment_invalid(self):
- with self.assertRaises(ConfigurationError):
- config.parse_environment('a=b')
- def test_parse_environment_empty(self):
- self.assertEqual(config.parse_environment(None), {})
- @mock.patch.dict(os.environ)
- def test_resolve_environment(self):
- os.environ['FILE_DEF'] = 'E1'
- os.environ['FILE_DEF_EMPTY'] = 'E2'
- os.environ['ENV_DEF'] = 'E3'
- service_dict = make_service_dict(
- 'foo', {
- 'build': '.',
- 'environment': {
- 'FILE_DEF': 'F1',
- 'FILE_DEF_EMPTY': '',
- 'ENV_DEF': None,
- 'NO_DEF': None
- },
- },
- 'tests/'
- )
- self.assertEqual(
- service_dict['environment'],
- {'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': ''},
- )
- def test_env_from_file(self):
- service_dict = make_service_dict(
- 'foo',
- {'build': '.', 'env_file': 'one.env'},
- 'tests/fixtures/env',
- )
- self.assertEqual(
- service_dict['environment'],
- {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'bar'},
- )
- def test_env_from_multiple_files(self):
- service_dict = make_service_dict(
- 'foo',
- {'build': '.', 'env_file': ['one.env', 'two.env']},
- 'tests/fixtures/env',
- )
- self.assertEqual(
- service_dict['environment'],
- {'ONE': '2', 'TWO': '1', 'THREE': '3', 'FOO': 'baz', 'DOO': 'dah'},
- )
- def test_env_nonexistent_file(self):
- options = {'env_file': 'nonexistent.env'}
- self.assertRaises(
- ConfigurationError,
- lambda: make_service_dict('foo', options, 'tests/fixtures/env'),
- )
- @mock.patch.dict(os.environ)
- def test_resolve_environment_from_file(self):
- os.environ['FILE_DEF'] = 'E1'
- os.environ['FILE_DEF_EMPTY'] = 'E2'
- os.environ['ENV_DEF'] = 'E3'
- service_dict = make_service_dict(
- 'foo',
- {'build': '.', 'env_file': 'resolve.env'},
- 'tests/fixtures/env',
- )
- self.assertEqual(
- service_dict['environment'],
- {'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': ''},
- )
- @mock.patch.dict(os.environ)
- def test_resolve_path(self):
- os.environ['HOSTENV'] = '/tmp'
- os.environ['CONTAINERENV'] = '/host/tmp'
- service_dict = config.load(
- config.ConfigDetails(
- config={'foo': {'build': '.', 'volumes': ['$HOSTENV:$CONTAINERENV']}},
- working_dir="tests/fixtures/env",
- filename=None,
- )
- )[0]
- self.assertEqual(set(service_dict['volumes']), set(['/tmp:/host/tmp']))
- service_dict = config.load(
- config.ConfigDetails(
- config={'foo': {'build': '.', 'volumes': ['/opt${HOSTENV}:/opt${CONTAINERENV}']}},
- working_dir="tests/fixtures/env",
- filename=None,
- )
- )[0]
- self.assertEqual(set(service_dict['volumes']), set(['/opt/tmp:/opt/host/tmp']))
- def load_from_filename(filename):
- return config.load(config.find('.', filename))
- class ExtendsTest(unittest.TestCase):
- def test_extends(self):
- service_dicts = load_from_filename('tests/fixtures/extends/docker-compose.yml')
- self.assertEqual(service_sort(service_dicts), service_sort([
- {
- 'name': 'mydb',
- 'image': 'busybox',
- 'command': 'top',
- },
- {
- 'name': 'myweb',
- 'image': 'busybox',
- 'command': 'top',
- 'links': ['mydb:db'],
- 'environment': {
- "FOO": "1",
- "BAR": "2",
- "BAZ": "2",
- },
- }
- ]))
- def test_nested(self):
- service_dicts = load_from_filename('tests/fixtures/extends/nested.yml')
- self.assertEqual(service_dicts, [
- {
- 'name': 'myweb',
- 'image': 'busybox',
- 'command': '/bin/true',
- 'environment': {
- "FOO": "2",
- "BAR": "2",
- },
- },
- ])
- def test_self_referencing_file(self):
- """
- We specify a 'file' key that is the filename we're already in.
- """
- service_dicts = load_from_filename('tests/fixtures/extends/specify-file-as-self.yml')
- self.assertEqual(service_sort(service_dicts), service_sort([
- {
- 'environment':
- {
- 'YEP': '1', 'BAR': '1', 'BAZ': '3'
- },
- 'image': 'busybox',
- 'name': 'myweb'
- },
- {
- 'environment':
- {'YEP': '1'},
- 'image': 'busybox',
- 'name': 'otherweb'
- },
- {
- 'environment':
- {'YEP': '1', 'BAZ': '3'},
- 'image': 'busybox',
- 'name': 'web'
- }
- ]))
- def test_circular(self):
- try:
- load_from_filename('tests/fixtures/extends/circle-1.yml')
- raise Exception("Expected config.CircularReference to be raised")
- except config.CircularReference as e:
- self.assertEqual(
- [(os.path.basename(filename), service_name) for (filename, service_name) in e.trail],
- [
- ('circle-1.yml', 'web'),
- ('circle-2.yml', 'web'),
- ('circle-1.yml', 'web'),
- ],
- )
- def test_extends_validation_empty_dictionary(self):
- with self.assertRaisesRegexp(ConfigurationError, 'service'):
- config.load(
- config.ConfigDetails(
- {
- 'web': {'image': 'busybox', 'extends': {}},
- },
- 'tests/fixtures/extends',
- 'filename.yml'
- )
- )
- def test_extends_validation_missing_service_key(self):
- with self.assertRaisesRegexp(ConfigurationError, "'service' is a required property"):
- config.load(
- config.ConfigDetails(
- {
- 'web': {'image': 'busybox', 'extends': {'file': 'common.yml'}},
- },
- 'tests/fixtures/extends',
- 'filename.yml'
- )
- )
- def test_extends_validation_invalid_key(self):
- expected_error_msg = "Unsupported config option for 'web' service: 'rogue_key'"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {
- 'web': {
- 'image': 'busybox',
- 'extends': {
- 'file': 'common.yml',
- 'service': 'web',
- 'rogue_key': 'is not allowed'
- }
- },
- },
- 'tests/fixtures/extends',
- 'filename.yml'
- )
- )
- def test_extends_validation_sub_property_key(self):
- expected_error_msg = "Service 'web' configuration key 'extends' 'file' contains an invalid type"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- config.load(
- config.ConfigDetails(
- {
- 'web': {
- 'image': 'busybox',
- 'extends': {
- 'file': 1,
- 'service': 'web',
- }
- },
- },
- 'tests/fixtures/extends',
- 'filename.yml'
- )
- )
- def test_extends_validation_no_file_key_no_filename_set(self):
- dictionary = {'extends': {'service': 'web'}}
- def load_config():
- return make_service_dict('myweb', dictionary, working_dir='tests/fixtures/extends')
- self.assertRaisesRegexp(ConfigurationError, 'file', load_config)
- def test_extends_validation_valid_config(self):
- service = config.load(
- config.ConfigDetails(
- {
- 'web': {'image': 'busybox', 'extends': {'service': 'web', 'file': 'common.yml'}},
- },
- 'tests/fixtures/extends',
- 'common.yml'
- )
- )
- self.assertEquals(len(service), 1)
- self.assertIsInstance(service[0], dict)
- self.assertEquals(service[0]['command'], "/bin/true")
- def test_extended_service_with_invalid_config(self):
- expected_error_msg = "Service 'myweb' has neither an image nor a build path specified"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- load_from_filename('tests/fixtures/extends/service-with-invalid-schema.yml')
- def test_extended_service_with_valid_config(self):
- service = load_from_filename('tests/fixtures/extends/service-with-valid-composite-extends.yml')
- self.assertEquals(service[0]['command'], "top")
- def test_extends_file_defaults_to_self(self):
- """
- Test not specifying a file in our extends options that the
- config is valid and correctly extends from itself.
- """
- service_dicts = load_from_filename('tests/fixtures/extends/no-file-specified.yml')
- self.assertEqual(service_sort(service_dicts), service_sort([
- {
- 'name': 'myweb',
- 'image': 'busybox',
- 'environment': {
- "BAR": "1",
- "BAZ": "3",
- }
- },
- {
- 'name': 'web',
- 'image': 'busybox',
- 'environment': {
- "BAZ": "3",
- }
- }
- ]))
- def test_invalid_links_in_extended_service(self):
- expected_error_msg = "services with 'links' cannot be extended"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- load_from_filename('tests/fixtures/extends/invalid-links.yml')
- def test_invalid_volumes_from_in_extended_service(self):
- expected_error_msg = "services with 'volumes_from' cannot be extended"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- load_from_filename('tests/fixtures/extends/invalid-volumes.yml')
- def test_invalid_net_in_extended_service(self):
- expected_error_msg = "services with 'net: container' cannot be extended"
- with self.assertRaisesRegexp(ConfigurationError, expected_error_msg):
- load_from_filename('tests/fixtures/extends/invalid-net.yml')
- @mock.patch.dict(os.environ)
- def test_valid_interpolation_in_extended_service(self):
- os.environ.update(
- HOSTNAME_VALUE="penguin",
- )
- expected_interpolated_value = "host-penguin"
- service_dicts = load_from_filename('tests/fixtures/extends/valid-interpolation.yml')
- for service in service_dicts:
- self.assertTrue(service['hostname'], expected_interpolated_value)
- def test_volume_path(self):
- dicts = load_from_filename('tests/fixtures/volume-path/docker-compose.yml')
- paths = [
- '%s:/foo' % os.path.abspath('tests/fixtures/volume-path/common/foo'),
- '%s:/bar' % os.path.abspath('tests/fixtures/volume-path/bar'),
- ]
- self.assertEqual(set(dicts[0]['volumes']), set(paths))
- def test_parent_build_path_dne(self):
- child = load_from_filename('tests/fixtures/extends/nonexistent-path-child.yml')
- self.assertEqual(child, [
- {
- 'name': 'dnechild',
- 'image': 'busybox',
- 'command': '/bin/true',
- 'environment': {
- "FOO": "1",
- "BAR": "2",
- },
- },
- ])
- def test_load_throws_error_when_base_service_does_not_exist(self):
- err_msg = r'''Cannot extend service 'foo' in .*: Service not found'''
- with self.assertRaisesRegexp(ConfigurationError, err_msg):
- load_from_filename('tests/fixtures/extends/nonexistent-service.yml')
- def test_partial_service_config_in_extends_is_still_valid(self):
- dicts = load_from_filename('tests/fixtures/extends/valid-common-config.yml')
- self.assertEqual(dicts[0]['environment'], {'FOO': '1'})
- class ExpandPathTest(unittest.TestCase):
- working_dir = '/home/user/somedir'
- def test_expand_path_normal(self):
- result = config.expand_path(self.working_dir, 'myfile')
- self.assertEqual(result, self.working_dir + '/' + 'myfile')
- def test_expand_path_absolute(self):
- abs_path = '/home/user/otherdir/somefile'
- result = config.expand_path(self.working_dir, abs_path)
- self.assertEqual(result, abs_path)
- def test_expand_path_with_tilde(self):
- test_path = '~/otherdir/somefile'
- with mock.patch.dict(os.environ):
- os.environ['HOME'] = user_path = '/home/user/'
- result = config.expand_path(self.working_dir, test_path)
- self.assertEqual(result, user_path + 'otherdir/somefile')
- class BuildPathTest(unittest.TestCase):
- def setUp(self):
- self.abs_context_path = os.path.join(os.getcwd(), 'tests/fixtures/build-ctx')
- def test_nonexistent_path(self):
- with self.assertRaises(ConfigurationError):
- config.load(
- config.ConfigDetails(
- {
- 'foo': {'build': 'nonexistent.path'},
- },
- 'working_dir',
- 'filename.yml'
- )
- )
- def test_relative_path(self):
- relative_build_path = '../build-ctx/'
- service_dict = make_service_dict(
- 'relpath',
- {'build': relative_build_path},
- working_dir='tests/fixtures/build-path'
- )
- self.assertEquals(service_dict['build'], self.abs_context_path)
- def test_absolute_path(self):
- service_dict = make_service_dict(
- 'abspath',
- {'build': self.abs_context_path},
- working_dir='tests/fixtures/build-path'
- )
- self.assertEquals(service_dict['build'], self.abs_context_path)
- def test_from_file(self):
- service_dict = load_from_filename('tests/fixtures/build-path/docker-compose.yml')
- self.assertEquals(service_dict, [{'name': 'foo', 'build': self.abs_context_path}])
- class GetConfigPathTestCase(unittest.TestCase):
- files = [
- 'docker-compose.yml',
- 'docker-compose.yaml',
- 'fig.yml',
- 'fig.yaml',
- ]
- def test_get_config_path_default_file_in_basedir(self):
- files = self.files
- self.assertEqual('docker-compose.yml', get_config_filename_for_files(files[0:]))
- self.assertEqual('docker-compose.yaml', get_config_filename_for_files(files[1:]))
- self.assertEqual('fig.yml', get_config_filename_for_files(files[2:]))
- self.assertEqual('fig.yaml', get_config_filename_for_files(files[3:]))
- with self.assertRaises(config.ComposeFileNotFound):
- get_config_filename_for_files([])
- def test_get_config_path_default_file_in_parent_dir(self):
- """Test with files placed in the subdir"""
- files = self.files
- def get_config_in_subdir(files):
- return get_config_filename_for_files(files, subdir=True)
- self.assertEqual('docker-compose.yml', get_config_in_subdir(files[0:]))
- self.assertEqual('docker-compose.yaml', get_config_in_subdir(files[1:]))
- self.assertEqual('fig.yml', get_config_in_subdir(files[2:]))
- self.assertEqual('fig.yaml', get_config_in_subdir(files[3:]))
- with self.assertRaises(config.ComposeFileNotFound):
- get_config_in_subdir([])
- def get_config_filename_for_files(filenames, subdir=None):
- def make_files(dirname, filenames):
- for fname in filenames:
- with open(os.path.join(dirname, fname), 'w') as f:
- f.write('')
- project_dir = tempfile.mkdtemp()
- try:
- make_files(project_dir, filenames)
- if subdir:
- base_dir = tempfile.mkdtemp(dir=project_dir)
- else:
- base_dir = project_dir
- return os.path.basename(config.get_config_path(base_dir))
- finally:
- shutil.rmtree(project_dir)
|