def test_plugin_object(self): with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir so that we can validate location mock_isdir.return_value = True plugin = Provider1PlugIn( "foo.provider", Provider1DefinitionTests.DEF_TEXT) self.assertIsInstance(plugin.plugin_object, Provider1)
def test_tr_description_combining(self): """ Verify that translated description is properly generated """ job = JobDefinition(self._split_description_record.data) def side_effect(arg): return { 'description': None, 'PURPOSE': 'TR_PURPOSE', 'STEPS': 'TR_STEPS', 'VERIFICATION': 'TR_VERIFICATION', 'purpose': 'tr_purpose_value', 'steps': 'tr_steps_value', 'verification': 'tr_verification_value' }[arg] with mock.patch.object(job, "get_translated_record_value") as mgtrv: mgtrv.side_effect = side_effect with mock.patch('plainbox.impl.unit.job._') as mock_gettext: mock_gettext.side_effect = side_effect retval = job.tr_description() mgtrv.assert_any_call('description') mgtrv.assert_any_call('purpose') mgtrv.assert_any_call('steps') mgtrv.assert_any_call('verification') self.assertEqual(mgtrv.call_count, 4) mock_gettext.assert_any_call('PURPOSE') mock_gettext.assert_any_call('STEPS') mock_gettext.assert_any_call('VERIFICATION') self.assertEqual(mock_gettext.call_count, 3) expected = ("TR_PURPOSE:\ntr_purpose_value\nTR_STEPS:\n" "tr_steps_value\nTR_VERIFICATION:\ntr_verification_value") self.assertEqual(retval, expected)
def test_definition_with_location(self): """ Smoke test to ensure we can load a typical provider definition that is using the location field and is not using any other directory fields. Those are similar to what a unpackaged, under development provider would look like. """ def_ = Provider1Definition() with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir so that we can validate all of the directory # variables. mock_isdir.return_value = True def_.read_string("[PlainBox Provider]\n" "name = 2013.org.example:smoke-test\n" "version = 1.0\n" "description = a description\n" "gettext_domain = domain\n" "location = /some/directory") self.assertEqual(def_.name, "2013.org.example:smoke-test") self.assertEqual(def_.version, "1.0") self.assertEqual(def_.description, "a description") self.assertEqual(def_.gettext_domain, "domain") self.assertEqual(def_.location, "/some/directory") self.assertEqual(def_.units_dir, Unset) self.assertEqual(def_.jobs_dir, Unset) self.assertEqual(def_.whitelists_dir, Unset) self.assertEqual(def_.data_dir, Unset) self.assertEqual(def_.bin_dir, Unset) self.assertEqual(def_.locale_dir, Unset)
def test_run_without_args(self, mock_check_output): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: with patch('plainbox.impl.commands.run.authenticate_warmup' ) as mock_warmup: mock_warmup.return_value = 0 main(['run']) self.assertEqual(call.exception.args, (0, )) expected1 = """ ===============================[ Analyzing Jobs ]=============================== Estimated duration cannot be determined for automated jobs. Estimated duration cannot be determined for manual jobs. ==============================[ Running All Jobs ]============================== ==================================[ Results ]=================================== """ expected2 = """ ===============================[ Authentication ]=============================== ===============================[ Analyzing Jobs ]=============================== Estimated duration cannot be determined for automated jobs. Estimated duration cannot be determined for manual jobs. ==============================[ Running All Jobs ]============================== ==================================[ Results ]=================================== """ self.assertIn(io.combined, [cleandoc(expected1) + "\n", cleandoc(expected2) + "\n"])
def test_definition_without_location(self): """ Smoke test to ensure we can load a typical provider definition that is not using the location field. Those are similar to what a packaged provider would look like. """ def_ = Provider1Definition() with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir so that we can validate all of the directory # variables. mock_isdir.return_value = True def_.read_string("[PlainBox Provider]\n" "name = org.example:smoke-test\n" "version = 1.0\n" "description = a description\n" "gettext_domain = domain\n" "units_dir = /some/directory/units\n" "jobs_dir = /some/directory/jobs\n" "data_dir = /some/directory/data\n" "bin_dir = /some/directory/bin\n" "locale_dir = /some/directory/locale\n") self.assertEqual(def_.name, "org.example:smoke-test") self.assertEqual(def_.version, "1.0") self.assertEqual(def_.description, "a description") self.assertEqual(def_.gettext_domain, "domain") self.assertEqual(def_.location, Unset) self.assertEqual(def_.units_dir, "/some/directory/units") self.assertEqual(def_.jobs_dir, "/some/directory/jobs") self.assertEqual(def_.data_dir, "/some/directory/data") self.assertEqual(def_.bin_dir, "/some/directory/bin") self.assertEqual(def_.locale_dir, "/some/directory/locale")
def test_load_session(self): """ verify that SessionManager.load_session() correctly delegates the task to various other objects """ job = mock.Mock(name='job', spec_set=JobDefinition) unit_list = [job] flags = None helper_name = "plainbox.impl.session.manager.SessionResumeHelper" with mock.patch(helper_name) as helper_cls: resumed_state = mock.Mock(spec_set=SessionState) resumed_state.unit_list = unit_list helper_cls().resume.return_value = resumed_state # NOTE: mock away _propagate_test_plans() so that we don't get # unwanted side effects we're not testing here. with mock.patch.object(SessionManager, '_propagate_test_plans'): manager = SessionManager.load_session(unit_list, self.storage) # Ensure that the storage object was used to load the session snapshot self.storage.load_checkpoint.assert_called_with() # Ensure that the helper was instantiated with the unit list, flags and # location helper_cls.assert_called_with(unit_list, flags, self.storage.location) # Ensure that the helper instance was asked to recreate session state helper_cls().resume.assert_called_with(self.storage.load_checkpoint(), None) # Ensure that the resulting manager has correct data inside self.assertEqual(manager.state, helper_cls().resume()) self.assertEqual(manager.storage, self.storage)
def test_run_without_args(self, mock_check_output): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: with patch('plainbox.impl.commands.run.authenticate_warmup') as mock_warmup: mock_warmup.return_value = 0 main(['run']) self.assertEqual(call.exception.args, (0,)) expected1 = """ ===============================[ Analyzing Jobs ]=============================== Estimated duration cannot be determined for automated jobs. Estimated duration cannot be determined for manual jobs. ==============================[ Running All Jobs ]============================== ==================================[ Results ]=================================== """ expected2 = """ ===============================[ Authentication ]=============================== ===============================[ Analyzing Jobs ]=============================== Estimated duration cannot be determined for automated jobs. Estimated duration cannot be determined for manual jobs. ==============================[ Running All Jobs ]============================== ==================================[ Results ]=================================== """ self.assertIn(io.combined, [ cleandoc(expected1) + "\n", cleandoc(expected2) + "\n"])
def test_definition_with_location(self): """ Smoke test to ensure we can load a typical provider definition that is using the location field and is not using any other directory fields. Those are similar to what a unpackaged, under development provider would look like. """ def_ = Provider1Definition() with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir so that we can validate all of the directory # variables. mock_isdir.return_value = True def_.read_string( "[PlainBox Provider]\n" "name = 2013.org.example:smoke-test\n" "version = 1.0\n" "description = a description\n" "gettext_domain = domain\n" "location = /some/directory" ) self.assertEqual(def_.name, "2013.org.example:smoke-test") self.assertEqual(def_.version, "1.0") self.assertEqual(def_.description, "a description") self.assertEqual(def_.gettext_domain, "domain") self.assertEqual(def_.location, "/some/directory") self.assertEqual(def_.jobs_dir, Unset) self.assertEqual(def_.whitelists_dir, Unset) self.assertEqual(def_.data_dir, Unset) self.assertEqual(def_.bin_dir, Unset) self.assertEqual(def_.locale_dir, Unset)
def test_plugin_name(self): with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir so that we can validate location mock_isdir.return_value = True plugin = Provider1PlugIn( "foo.provider", Provider1DefinitionTests.DEF_TEXT) self.assertEqual( plugin.plugin_name, "2013.org.example:smoke-test")
def test_init_validation__location_doesnt_exist(self): """ verify that Provider1Definition ensures that 'location' field is not pointing to an non-existing directory """ def_ = Provider1Definition() with self.assertRaises(ValidationError) as boom: with mock.patch('os.path.isdir') as mock_isdir: mock_isdir.return_value = False def_.location = '/some/place' self.assertEqual(str(boom.exception), "no such directory")
def test_output_format_list(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: with patch('plainbox.impl.commands.run.get_all_exporters') as mock_get_all_exporters: mock_get_all_exporters.return_value = self._exporters main(['run', '--output-format=?']) self.assertEqual(call.exception.args, (0,)) expected = """ Available output formats: json, rfc822, text, xml """ self.assertEqual(io.combined, cleandoc(expected) + "\n")
def test_smoke(self): with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir so that we can validate location mock_isdir.return_value = True self.definition.read_string(self.DEF_TEXT) self.assertEqual(self.definition.location, "/some/directory/") self.assertEqual(self.definition.name, "2013.org.example:smoke-test") self.assertEqual(self.definition.version, "1.0") self.assertEqual( self.definition.description, "A provider for smoke testing") self.assertEqual(self.definition.gettext_domain, "plainbox")
def test_provider_data(self): with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir so that we can validate location mock_isdir.return_value = True plugin = Provider1PlugIn( "foo.provider", Provider1DefinitionTests.DEF_TEXT) provider = plugin.plugin_object self.assertEqual(provider.base_dir, "/some/directory/") self.assertEqual(provider.name, "2013.org.example:smoke-test") self.assertEqual(provider.version, "1.0") self.assertEqual(provider.description, "A provider for smoke testing")
def test_add_local_device_context(self): """ Ensure that using add_local_device_context() adds a context with a special 'local' device and fires the appropriate signal """ manager = SessionManager([], self.storage) self.watchSignal(manager.on_device_context_added) cls_name = "plainbox.impl.session.manager.SessionDeviceContext" with mock.patch(cls_name) as sdc: manager.add_local_device_context() self.assertSignalFired(manager.on_device_context_added, sdc()) self.assertIn(sdc(), manager.device_context_list)
def test_output_format_list(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: with patch('plainbox.impl.commands.run.get_all_exporters' ) as mock_get_all_exporters: mock_get_all_exporters.return_value = self._exporters main(['run', '--output-format=?']) self.assertEqual(call.exception.args, (0, )) expected = """ Available output formats: json, rfc822, text, xml """ self.assertEqual(io.combined, cleandoc(expected) + "\n")
def mocked_file(self, name, content): m_open = mock.MagicMock(name='open', spec=open) m_stream = mock.MagicMock(spec=TextIOWrapper) m_stream.__enter__.return_value = m_stream # The next two lines are complementary, either will suffice but the # test may need changes if the code that reads stuff changes. m_stream.__iter__.side_effect = lambda: iter(content) m_stream.read.return_value = "\n".join(content) m_open.return_value = m_stream with mock.patch('plainbox.impl.secure.qualifiers.open', m_open, create=True): yield m_open.assert_called_once_with(name, "rt", encoding="UTF-8")
def test_init_validation__foo_dir_doesnt_exist(self): """ verify that Provider1Definition ensures that 'jobs_dir', 'whitelists_dir', 'data_dir', 'bin_dir' and 'locale_dir' fields are not pointing to a non-existing directory """ for attr in ('jobs_dir', 'whitelists_dir', 'data_dir', 'bin_dir', 'locale_dir'): def_ = Provider1Definition() with self.assertRaises(ValidationError) as boom: with mock.patch('os.path.isdir') as mock_isdir: mock_isdir.return_value = False setattr(def_, attr, '/some/place') self.assertEqual(str(boom.exception), "no such directory")
def test_init_validation__foo_dir_doesnt_exist(self): """ verify that Provider1Definition ensures that 'jobs_dir', 'whitelists_dir', 'data_dir', 'bin_dir' and 'locale_dir' fields are not pointing to a non-existing directory """ for attr in ('units_dir', 'jobs_dir', 'whitelists_dir', 'data_dir', 'bin_dir', 'locale_dir'): def_ = Provider1Definition() with self.assertRaises(ValidationError) as boom: with mock.patch('os.path.isdir') as mock_isdir: mock_isdir.return_value = False setattr(def_, attr, '/some/place') self.assertEqual(str(boom.exception), "no such directory")
def test_output_option_list(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: with patch('plainbox.impl.commands.run.get_all_exporters') as mock_get_all_exporters: mock_get_all_exporters.return_value = self._exporters main(['run', '--output-option=?']) self.assertEqual(call.exception.args, (0,)) expected = """ Each format may support a different set of options json: with-io-log, squash-io-log, flatten-io-log, with-run-list, with-job-list, with-resource-map, with-job-defs, with-attachments, with-comments, with-job-via, with-job-hash, machine-json rfc822: with-io-log, squash-io-log, flatten-io-log, with-run-list, with-job-list, with-resource-map, with-job-defs, with-attachments, with-comments, with-job-via, with-job-hash text: with-io-log, squash-io-log, flatten-io-log, with-run-list, with-job-list, with-resource-map, with-job-defs, with-attachments, with-comments, with-job-via, with-job-hash xml: """ self.assertEqual(io.combined, cleandoc(expected) + "\n")
def setUp(self): with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir so that we can validate location mock_isdir.return_value = True self.plugin = Provider1PlugIn("a.provider", self.DEF_TEXT) self.plugin_w_location = Provider1PlugIn( "a.provider", self.DEF_TEXT_w_location) self.plugin_w_dirs = Provider1PlugIn( "a.provider", self.DEF_TEXT_w_dirs) # Mock os.path.isdir so that none of the sub-directories of the # location directory seem to exist. This is essential for # Provider1.from_definition()'s special behavior. mock_isdir.side_effect = lambda dn: dn == "/some/directory" self.plugin_w_location_w_no_dirs = Provider1PlugIn( "a.provider", self.DEF_TEXT_w_location)
def test_output_option_list(self): with TestIO(combined=True) as io: with self.assertRaises(SystemExit) as call: with patch('plainbox.impl.commands.run.get_all_exporters' ) as mock_get_all_exporters: mock_get_all_exporters.return_value = self._exporters main(['run', '--output-option=?']) self.assertEqual(call.exception.args, (0, )) expected = """ Each format may support a different set of options json: with-io-log, squash-io-log, flatten-io-log, with-run-list, with-job-list, with-resource-map, with-job-defs, with-attachments, with-comments, with-job-via, with-job-hash, machine-json rfc822: with-io-log, squash-io-log, flatten-io-log, with-run-list, with-job-list, with-resource-map, with-job-defs, with-attachments, with-comments, with-job-via, with-job-hash text: with-io-log, squash-io-log, flatten-io-log, with-run-list, with-job-list, with-resource-map, with-job-defs, with-attachments, with-comments, with-job-via, with-job-hash xml: """ self.assertEqual(io.combined, cleandoc(expected) + "\n")
def test_init__without_PROVIDERPATH_set(self): """ validate that InsecureProvider1PlugInCollection() has working defaults if PROVIDERPATH are not in env """ real_os_getenv = os.getenv def getenv(*args): if args[0] == 'PROVIDERPATH': return None else: return real_os_getenv(*args) with mock.patch('os.getenv') as mock_getenv: mock_getenv.side_effect = getenv obj = InsecureProvider1PlugInCollection() self.assertTrue(len(obj._dir_list) > 0)
def test_init_validation__non_iqn_name(self): """ verify how Provider1PlugIn validates missing name field """ with self.assertRaises(PlugInError) as boom: with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir so that we can validate location mock_isdir.return_value = True Provider1PlugIn("broken.provider", ( "[PlainBox Provider]\n" "name = my pretty name\n" "version = 1.0\n" "location = /some/place\n" )) self.assertEqual( str(boom.exception), ( "Problem in provider definition, " "field 'name': must look like RFC3720 IQN"))
def test_init_validation__location_is_empty(self): """ verify how Provider1PlugIn validates missing location field """ with self.assertRaises(PlugInError) as boom: with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir so that we can validate location mock_isdir.return_value = True Provider1PlugIn("broken.provider", ( "[PlainBox Provider]\n" "name = 2014.example.org:name\n" "version = 1.0\n" "location =\n" )) self.assertEqual( str(boom.exception), ( "Problem in provider definition, " "field 'location': cannot be empty"))
def test_init_validation__no_location(self): """ verify how Provider1PlugIn validates missing location field """ with self.assertRaises(PlugInError) as boom: with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir so that we can validate location mock_isdir.return_value = True Provider1PlugIn("broken.provider", ( "[PlainBox Provider]\n" "name = 2014.example.org:name\n" "version = 1.0\n" # NOTE: no location set, we should see that being caught # "location = /some/place\n" )) self.assertEqual( str(boom.exception), ( "Problem in provider definition, " "field 'location': must be set to something"))
def test_checkpoint(self): """ verify that SessionManager.checkpoint() creates an image of the suspended session and writes it using the storage system. """ # Mock the suspend helper, we don't want to suspend our mock objects helper_name = "plainbox.impl.session.manager.SessionSuspendHelper" with mock.patch(helper_name, spec=SessionSuspendHelper) as helper_cls: # Call the tested method self.manager.checkpoint() # Ensure that a fresh instance of the suspend helper was used to # call the suspend() method and that the session state parameter # was passed to it. helper_cls().suspend.assert_called_with(self.context.state, self.storage.location) # Ensure that save_checkpoint() was called on the storage object with # the return value of what the suspend helper produced. self.storage.save_checkpoint.assert_called_with(helper_cls().suspend( self.context.state))
def test_init_validation__location_doesnt_exist(self): """ verify how Provider1PlugIn validates location field pointing to a directory that does not exist """ with self.assertRaises(PlugInError) as boom: with mock.patch('os.path.isdir') as mock_isdir: # Mock os.path.isdir the *other* way around, so that this # directory doesn't exist, even if it does somehow mock_isdir.return_value = False Provider1PlugIn("broken.provider", ( "[PlainBox Provider]\n" "name = 2014.example.org:name\n" "version = 1.0\n" "location = /some/place\n" )) self.assertEqual( str(boom.exception), ( "Problem in provider definition, " "field 'location': no such directory"))
def test_checkpoint(self): """ verify that SessionManager.checkpoint() creates an image of the suspended session and writes it using the storage system. """ storage = mock.Mock(name="storage", spec=SessionStorage) state = mock.Mock(name="state", spec=SessionState) manager = SessionManager(state, storage) # Mock the suspend helper, we don't want to suspend our mock objects helper_name = "plainbox.impl.session.manager.SessionSuspendHelper" with mock.patch(helper_name, spec=SessionSuspendHelper) as helper_cls: # Call the tested method manager.checkpoint() # Ensure that a fresh instance of the suspend helper was used to # call the suspend() method and that the session state parameter # was passed to it. helper_cls().suspend.assert_called_with(state) # Ensure that save_checkpoint() was called on the storage object with # the return value of what the suspend helper produced. storage.save_checkpoint.assert_called_with(helper_cls().suspend(state))
def test_load_session(self): """ verify that SessionManager.load_session() correctly delegates the task to various other objects """ # Mock SessionState and job list storage = mock.Mock(name="storage", spec=SessionStorage) job_list = mock.Mock(name='job_list') helper_name = "plainbox.impl.session.manager.SessionResumeHelper" with mock.patch(helper_name) as helper_cls: helper_cls().resume.return_value = mock.Mock(name="state", spec=SessionState) manager = SessionManager.load_session(job_list, storage) # Ensure that the storage object was used to load the session snapshot storage.load_checkpoint.assert_called_with() # Ensure that the helper was instantiated with the job list helper_cls.assert_called_with(job_list) # Ensure that the helper instance was asked to recreate session state helper_cls().resume.assert_called_with(storage.load_checkpoint(), None) # Ensure that the resulting manager has correct data inside self.assertEqual(manager.state, helper_cls().resume()) self.assertEqual(manager.storage, storage)
def test_load_session(self): """ verify that SessionManager.load_session() correctly delegates the task to various other objects """ # Mock SessionState and job list storage = mock.Mock(name="storage", spec=SessionStorage) job_list = mock.Mock(name='job_list') helper_name = "plainbox.impl.session.manager.SessionResumeHelper" with mock.patch(helper_name) as helper_cls: helper_cls().resume.return_value = mock.Mock( name="state", spec=SessionState) manager = SessionManager.load_session(job_list, storage) # Ensure that the storage object was used to load the session snapshot storage.load_checkpoint.assert_called_with() # Ensure that the helper was instantiated with the job list helper_cls.assert_called_with(job_list) # Ensure that the helper instance was asked to recreate session state helper_cls().resume.assert_called_with(storage.load_checkpoint(), None) # Ensure that the resulting manager has correct data inside self.assertEqual(manager.state, helper_cls().resume()) self.assertEqual(manager.storage, storage)
def setUp(self): self.sample_xml = BytesIO(resource_string( "plainbox", "test-data/xml-exporter/example-data.xml" )) self.patcher = mock.patch('requests.post') self.mock_requests = self.patcher.start()
def setUp(self): self.sample_archive = BytesIO(resource_string( "plainbox", "test-data/tar-exporter/example-data.tar.xz" )) self.patcher = mock.patch('requests.post') self.mock_requests = self.patcher.start()
def setUp(self): with mock.patch('os.path.exists') as mock_exists: mock_exists.return_value = True self.provider = CheckBoxSrcProvider()