def test_add_module(self, mock_shutil): module_path = '/tmp/mod.tar.gz' feed_url = 'http://host/root/PULP_MANAFEST' unit_key = {'name': 'puppet-module'} unit_metadata = {'A': 1, 'B': 2} unit = Mock() unit.storage_path = '/tmp/%s' % uuid4() mock_conduit = Mock() mock_conduit.init_unit = Mock(return_value=unit) config = {constants.CONFIG_FEED: feed_url} mock_module = Mock() mock_module.unit_key = Mock(return_value=unit_key) mock_module.unit_metadata = Mock(return_value=unit_metadata) mock_module.filename = Mock(return_value='puppet-module') # test method = SynchronizeWithDirectory(mock_conduit, config) method._add_module(module_path, mock_module) # validation mock_conduit.init_unit.assert_called_with( constants.TYPE_PUPPET_MODULE, unit_key, unit_metadata, mock_module.filename()) mock_shutil.copy.assert_called_with(module_path, unit.storage_path)
def test_add_module(self, mock_shutil): module_path = '/tmp/mod.tar.gz' feed_url = 'http://host/root/PULP_MANAFEST' unit_key = {'name': 'puppet-module'} unit_metadata = {'A': 1, 'B': 2} unit = Mock() unit.storage_path = '/tmp/%s' % uuid4() mock_conduit = Mock() mock_conduit.init_unit = Mock(return_value=unit) config = {constants.CONFIG_FEED: feed_url} mock_module = Mock() mock_module.unit_key = Mock(return_value=unit_key) mock_module.unit_metadata = Mock(return_value=unit_metadata) mock_module.filename = Mock(return_value='puppet-module') # test method = SynchronizeWithDirectory(mock_conduit, config) method._add_module(module_path, mock_module) # validation mock_conduit.init_unit.assert_called_with(constants.TYPE_PUPPET_MODULE, unit_key, unit_metadata, mock_module.filename()) mock_shutil.copy.assert_called_with(module_path, unit.storage_path)
def test_ignore(self): evt = Mock() evt.filename = "event.txt" if not self.test_obj.__ignore__: self.assertFalse(self.test_obj.ignore(evt)) else: self.assertFalse(self.test_obj.ignore(evt)) for extension in self.test_obj.__ignore__: for name in ["event.txt", "....", extension, "." + extension]: for filler in ['', '.blah', '......', '.' + extension]: evt.filename = name + filler + '.' + extension self.assertTrue(self.test_obj.ignore(evt))
def test_ignore(self): evt = Mock() evt.filename = "event.txt" if not self.test_obj.__ignore__: self.assertFalse(self.test_obj.ignore(evt)) else: self.assertFalse(self.test_obj.ignore(evt)) for extension in self.test_obj.__ignore__: for name in ["event.txt", "....", extension, "." + extension]: for filler in ["", ".blah", "......", "." + extension]: evt.filename = name + filler + "." + extension self.assertTrue(self.test_obj.ignore(evt))
def test_add_module_not_copied(self, mock_shutil): module_path = '/tmp/mod.tar.gz' feed_url = 'http://host/root/PULP_MANAFEST' unit_key = {'name': 'puppet-module'} unit_metadata = {'A': 1, 'B': 2} unit = Mock() unit.storage_path = os.path.join(os.getcwd(), __file__) mock_conduit = Mock() mock_conduit.init_unit = Mock(return_value=unit) config = {constants.CONFIG_FEED: feed_url} mock_module = Mock() mock_module.unit_key = Mock(return_value=unit_key) mock_module.unit_metadata = Mock(return_value=unit_metadata) mock_module.filename = Mock(return_value='puppet-module') # test method = SynchronizeWithDirectory(mock_conduit, config) method._add_module(module_path, mock_module) # validation self.assertFalse(mock_shutil.copy.called)
def _mock(self, val): # Mock has an attr `mixed`, which inadvertantly gets called by formencode to_python method :/ def f(filename): pass m = Mock(spec=f) m.filename = val return m
def setup_mock_options(cls, hosts=None, filename=None, grouping=None): mock_options = Mock(spec=['hosts', 'filename', 'verbosity', 'min_instance_count', 'grouping']) mock_options.hosts = hosts mock_options.filename = filename mock_options.verbosity = False mock_options.grouping = grouping or DEFAULT_GROUPING return mock_options
def _new_dialplan_parse_result(self, filename='test', lines=None): if lines is None: lines = [] dialplan_parse_result = Mock() dialplan_parse_result.filename = filename dialplan_parse_result.lines = lines return dialplan_parse_result
def test_upload_an_image_twice(self, ImageTruck, delay): truck = Mock() ImageTruck.new_from_stream.return_value = truck truck.filename = 'CA7' truck.url.return_value = 'ess three' truck.contents = b'' truck.content_type = "image/jpeg" response = self.app.post('/add', data={ 'url': '', 'file': (StringIO(str('booya')), 'img.jpg')}) eq_(response.status_code, 302) response = self.app.post('/add', data={ 'url': '', 'file': (StringIO(str('booya')), 'img.jpg')}) eq_(response.status_code, 302) session = Client().session() image = session.query(Image).one() contentses = session.query(ImageContents).all() for contents in contentses: eq_(contents.image_id, image.image_id) contents_calls = [call([], process_image, x.image_contents_id) for x in contentses] delay.assert_has_calls(contents_calls)
def test_entry_init(self, mock_entry_init): eset = self.get_obj() eset.entries = dict() evt = Mock() evt.filename = "test.txt" handler = Mock() handler.__basenames__ = [] handler.__extensions__ = [] handler.deprecated = False handler.experimental = False handler.__specific__ = True # test handling an event with the parent entry_init eset.entry_init(evt, handler) mock_entry_init.assert_called_with(eset, evt, entry_type=handler, specific=handler.get_regex.return_value) self.assertItemsEqual(eset.entries, dict()) # test handling the event with a Cfg handler handler.__specific__ = False eset.entry_init(evt, handler) handler.assert_called_with(os.path.join(eset.path, evt.filename)) self.assertItemsEqual(eset.entries, {evt.filename: handler.return_value}) handler.return_value.handle_event.assert_called_with(evt) # test handling an event for an entry that already exists with # a Cfg handler handler.reset_mock() eset.entry_init(evt, handler) self.assertFalse(handler.called) self.assertItemsEqual(eset.entries, {evt.filename: handler.return_value}) eset.entries[evt.filename].handle_event.assert_called_with(evt)
def test_get_template_path(): temp_dirs = ["tests/fixtures/template-tests", "tests/abc", "tests/abc"] template = Mock() template.filename = "a.jj2" template_path = get_template_path(temp_dirs, template) expected = os.path.join(os.getcwd(), "tests/fixtures/template-tests/a.jj2") eq_(template_path, expected)
def test_end_step(self): feature = Mock() feature.filename = 'foo/bar.md' feature.description = u'This is an example.' feature.tags = [] feature.scenarios = [] scenario = Mock() scenario.name = 'Scenario 1' scenario.status = 'passed' feature.scenarios.append(scenario) context = Mock() def side_effect(arg): raise Exception('No browser') context.browser.driver.get_screenshot_as_file = side_effect self.maker.start_feature(context, feature) self.maker.start_scenario(context, scenario) step = Mock() step.keyword = u'foo' step.name = u'bar' step.status = u'passed' step.duration = 1.01 self.maker.end_step(context, step) step_line = 'foo bar | passed | 1.01 | error capturing' self.assertIn(step_line, self.maker.doc.getcontents())
def test_HandleEvent(self, mock_load_xml): config = self.get_config_object("groups.xml") evt = Mock() evt.filename = os.path.join(self.metadata.data, "groups.xml") evt.code2str = Mock(return_value="changed") self.assertTrue(config.HandleEvent(evt)) mock_load_xml.assert_called_with()
def test_upload_an_image(self, ImageTruck, delay): truck = Mock() ImageTruck.new_from_stream.return_value = truck truck.filename = 'CA7' truck.url.return_value = 'ess three' truck.contents = b'' truck.content_type = "image/jpeg" session = Client().session() album = Album(name='11:11 Eleven Eleven') session.add(album) session.flush() response = self.app.post('/add', data={ 'url': '', 'album_id': album.album_id, 'file': (StringIO(str('booya')), 'img.jpg')}) image = session.query(Image).one() eq_(image.filename, 'CA7') eq_(image.source_url, '') eq_(image.album_id, album.album_id) eq_(response.status_code, 302, response.data) eq_(response.headers['Location'], 'http://localhost/image/{0}'.format(image.image_id)) contents = session.query(ImageContents).one() eq_(image.image_id, contents.image_id) delay.assert_called_with( [], process_image, contents.image_contents_id)
def test_entry_init(self, mock_entry_init): eset = self.get_obj() eset.entries = dict() evt = Mock() evt.filename = "test.txt" handler = Mock() handler.__specific__ = True # test handling an event with the parent entry_init eset.entry_init(evt, handler) mock_entry_init.assert_called_with(eset, evt, entry_type=handler, specific=handler.get_regex.return_value) self.assertItemsEqual(eset.entries, dict()) # test handling the event with a Cfg handler handler.__specific__ = False eset.entry_init(evt, handler) handler.assert_called_with(os.path.join(eset.path, evt.filename)) self.assertItemsEqual(eset.entries, {evt.filename: handler.return_value}) handler.return_value.handle_event.assert_called_with(evt) # test handling an event for an entry that already exists with # a Cfg handler handler.reset_mock() eset.entry_init(evt, handler) self.assertFalse(handler.called) self.assertItemsEqual(eset.entries, {evt.filename: handler.return_value}) eset.entries[evt.filename].handle_event.assert_called_with(evt)
def make_mock_options(self): mock_options = Mock() mock_options.filename = None mock_options.hosts = ','.join(self.HOSTNAMES) mock_options.cluster = self.TEST_CLUSTER mock_options.verbosity = False return mock_options
def test_handles(self, mock_get_regex): match = Mock() mock_get_regex.return_value = Mock() mock_get_regex.return_value.match = match evt = Mock() evt.filename = "event.txt" if self.test_obj.__basenames__: match.return_value = False self.assertFalse(self.test_obj.handles(evt)) mock_get_regex.assert_called_with([b for b in self.test_obj.__basenames__]) print("match calls: %s" % match.call_args_list) print("expected: %s" % [call(evt.filename) for b in self.test_obj.__basenames__]) match.assert_called_with(evt.filename) mock_get_regex.reset_mock() match.reset_mock() match.return_value = True self.assertTrue(self.test_obj.handles(evt)) match.assert_called_with(evt.filename) else: match.return_value = False self.assertFalse(self.test_obj.handles(evt, basename=os.path.basename(self.path))) mock_get_regex.assert_called_with([os.path.basename(self.path)]) match.assert_called_with(evt.filename) mock_get_regex.reset_mock() match.reset_mock() match.return_value = True self.assertTrue(self.test_obj.handles(evt, basename=os.path.basename(self.path))) mock_get_regex.assert_called_with([os.path.basename(self.path)]) match.assert_called_with(evt.filename)
def test_upload_an_image_with_json_format(self, ImageTruck, delay): truck = Mock() ImageTruck.new_from_url.return_value = truck truck.filename = 'CA741C' truck.url.return_value = 'cloudfrunt.nut/CA741C' truck.contents = b'' truck.content_type = "image/gif" task_id = str(uuid.uuid4()) delay.return_value = task_id response = self.app.post('/add.json', data={ 'album': '', 'url': 'imgur.com/cool_cat.gif'}) eq_(response.status_code, 200, response.data) session = Client().session() image = session.query(Image).one() body = json.loads(response.data) eq_(body, [{ 'url': 'cloudfrunt.nut/CA741C', 'image_id': image.image_id, 'task_id': task_id, }]) contents = session.query(ImageContents).one() eq_(contents.image_id, image.image_id) delay.assert_called_with([], process_image, contents.image_contents_id)
def mock_truck(self): truck = Mock() with open(SOME_GIF, 'r') as fh: truck.contents = fh.read() truck.url.return_value = 'https://catsnap.cdn/ca7face' truck.filename = 'ca7face' truck.content_type = 'image/gif' return truck
def setup_mock_options(cls, hosts=None, filename=None, grouping=None): mock_options = Mock(spec=[ 'hosts', 'filename', 'verbosity', 'min_instance_count', 'grouping' ]) mock_options.hosts = hosts mock_options.filename = filename mock_options.verbosity = False mock_options.grouping = grouping or DEFAULT_GROUPING return mock_options
def test_start_feature(self): feature = Mock() feature.filename = 'foo/bar.md' feature.description = u'This is an example.' feature.tags = [] context = Mock() self.maker.start_feature(context, feature) self.assertIn('This is an example.', self.maker.doc.getcontents()) dir_name = self.maker.output_dir + '/' + self.maker.doc.path assert os.path.isdir(dir_name)
def test_upload_filedata_returns_false_if_extension_not_correct(self): # given uploaded_file = Mock() uploaded_file.filename = 'filename.oops' # when success = upload_filedata(uploaded_file) # then self.assertFalse(success)
def load_groups_data(self, metadata=None, xdata=None): if metadata is None: metadata = get_metadata_object() metadata.groups_xml.data = xdata or copy.deepcopy(groups_test_tree) metadata.groups_xml.basedata = copy.copy(metadata.groups_xml.data) evt = Mock() evt.filename = os.path.join(datastore, "Metadata", "groups.xml") evt.code2str = Mock(return_value="changed") metadata.HandleEvent(evt) return metadata
def make_mock_options(self): mock_options = Mock() mock_options.filename = None mock_options.hosts = ','.join(self.HOSTNAMES) mock_options.cluster = self.TEST_CLUSTER mock_options.verbosity = False mock_options.disable_all_hooks = False mock_options.percentage = None mock_options.duration = None mock_options.reason = None return mock_options
def test_anonymous_returns_http_200(self, mock_blob_api_get_by_id): mock_blob = Mock() mock_blob.blob = "blob_text" mock_blob.filename = "blob.txt" mock_blob_api_get_by_id.return_value = mock_blob response = RequestMock.do_request_get( blob_rest_views.BlobDownload.as_view(), None, param={"pk": "0"}) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_add_gcode_file(self): fake = Mock() fake.filename = "test_stl.gcode" self.filenames.append(fake.filename) fake.__getitem__ = "SOMETHING" result, done = self.manager.addFile(fake, FileDestinations.LOCAL) logging.info("RESULT:%s" % str(result)) self.assertTrue(fake.filename == result) self.assertTrue(done)
def test_upload_filedata_raises_exception_if_parsing_empty(self, mock_save_file, mock_parse): # given uploaded_file = Mock() uploaded_file.filename = 'filename.csv' mock_parse.return_value = [] # when mock_save_file.return_value = True # then with self.assertRaises(NoItemsGeneratedFromParsingException): upload_filedata(uploaded_file)
def test_HandleEvent(self): ps = self.get_obj() ps.handle_event = Mock() # test that events on the data store itself are skipped evt = Mock() evt.filename = datastore ps.HandleEvent(evt) self.assertFalse(ps.handle_event.called) # test that events on probed.xml are skipped evt.reset_mock() evt.filename = "probed.xml" ps.HandleEvent(evt) self.assertFalse(ps.handle_event.called) # test that other events are processed appropriately evt.reset_mock() evt.filename = "fooprobe" ps.HandleEvent(evt) ps.handle_event.assert_called_with(evt)
def test_fetch_zip_processing(self, mockZipFile): self.fetcher.mock_remote_result = ('fake-content-from', 'zip', 'fake-content') mockMember = Mock() mockMember.filename = 'fake-filename' mockZipFile.return_value.__enter__.return_value.filelist = [mockMember] self.fetcher.fetch({'to': 'fake-to'}) mockZipFile.assert_called_once() mockZipFile.return_value.__enter__.return_value\ .extract.assert_called_once_with( mockMember, 'fake-shared-template-dir/fake-to' )
def test_upload_tempalte_list(self): "Filename can be a list of filename for get_or_select_template." with patch('argyle.base.Environment') as mock_environment: mock_env = Mock() mock_template = Mock() mock_template.filename = 'bar.txt' # Second template is used mock_env.get_or_select_template.return_value = mock_template mock_environment.return_value = mock_env upload_template(['foo.txt', 'bar.txt'] , '/tmp/') put = self.mocks['put'] self.assertTrue(put.called) args, kwargs = put.call_args self.assertEqual(kwargs['remote_path'], '/tmp/bar.txt')
def test_upload_filedata_raises_exception_if_parsing_empty( self, mock_save_file, mock_parse): # given uploaded_file = Mock() uploaded_file.filename = 'filename.csv' mock_parse.return_value = [] # when mock_save_file.return_value = True # then with self.assertRaises(NoItemsGeneratedFromParsingException): upload_filedata(uploaded_file)
def make_mock_options(self): mock_options = Mock() mock_options.filename = None mock_options.hosts = ','.join(self.HOSTNAMES) mock_options.cluster = self.TEST_CLUSTER mock_options.verbosity = False mock_options.disable_all_hooks = False mock_options.percentage = None mock_options.duration = None mock_options.reason = None mock_options.default_duration = '30m' mock_options.default_percentage = self.DEFAULT_SLA_PERCENTAGE mock_options.timeout = '2h' return mock_options
def inner(mock_add_entry, mock_event_path): modules = self.get_obj() evt = Mock() evt.filename = "test.pp.G10_foo" mock_event_path.return_value = os.path.join(datastore, self.test_obj.__name__, "test.pp", "test.pp.G10_foo") modules.add_entry(evt) self.assertEqual(modules.filename_pattern, "test.pp") mock_add_entry.assert_called_with(modules, evt) mock_event_path.assert_called_with(evt)
def _opml(self, opml, urls, feed): for u in urls: HTTPretty.register_uri(HTTPretty.GET, u, body=feed, content_type='application/rss+xml') upload = Mock() upload.file = StringIO(opml) upload.filename = 'opml.xml' params = {'opml': {'upload': upload}, 'import': 'submit', '__formid__': 'form2', } request = testing.DummyRequest(post=params) response = view_feedadd(request) return response
def test_staff_returns_http_200(self, mock_blob_api_get_by_id): mock_blob = Mock() mock_blob.blob = "blob_text" mock_blob.filename = "blob.txt" mock_blob_api_get_by_id.return_value = mock_blob mock_user = create_mock_user("1", is_staff=True) response = RequestMock.do_request_get( blob_rest_views.BlobDownload.as_view(), mock_user, param={"pk": "0"}) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_start_scenario(self): feature = Mock() feature.filename = 'foo/bar.md' feature.description = u'This is an example.' feature.tags = [] feature.scenarios = [] scenario = Mock() scenario.name = 'Scenario 1' scenario.status = 'passed' feature.scenarios.append(scenario) context = Mock() self.maker.start_feature(context, feature) self.maker.start_scenario(context, scenario) scenario_line = '### %s' % scenario.name self.assertIn(scenario_line, self.maker.doc.getcontents())
def test_add_stl_file_curaDisabled(self, process, getterMock): getterMock.return_value = False fake = Mock() fake.filename = "test_stl.stl" self.filenames.append(fake.filename) fake.__getitem__ = "SOMETHING" result, done = self.manager.addFile(fake, FileDestinations.LOCAL) logging.info("RESULT:%s" % str(result)) self.assertFalse(process.called) self.assertIsNone(result) self.assertTrue(done)
def inner(mock_add_entry): modules = self.get_obj() modules.event_path = Mock() evt = Mock() evt.filename = "test.pp.G10_foo" modules.event_path.return_value = \ os.path.join(datastore, self.test_obj.__name__, "test.pp", "test.pp.G10_foo") modules.add_entry(evt) self.assertEqual(modules.filename_pattern, "test.pp") mock_add_entry.assert_called_with(modules, evt) modules.event_path.assert_called_with(evt)
def test_end_feature(self): feature = Mock() feature.filename = 'foo/bar.md' feature.description = u'This is an example.' feature.tags = [] feature.scenarios = [] scenario = Mock() scenario.name = 'Scenario 1' scenario.status = 'passed' feature.scenarios.append(scenario) context = Mock() self.maker.start_feature(context, feature) self.maker.end_feature(context, feature) num_scenarios = 'num_scenarios = "1"' num_scenarios_passing = 'num_scenarios_passing = "1"' self.assertIn(num_scenarios, self.maker.doc.header()) self.assertIn(num_scenarios_passing, self.maker.doc.header())
def test_add_stl_file_curaEnabled(self, process, getterMock): getterMock.return_value = True fake = Mock() fake.filename = "test_stl.stl" self.filenames.append(fake.filename) fake.__getitem__ = "SOMETHING" result, done = self.manager.addFile(fake, FileDestinations.LOCAL) logging.info("RESULT:%s" % str(result)) getterMock.assert_called_once_with(["cura", "enabled"]) self.assertTrue(process.called) self.assertTrue("test_stl.gcode" == result) self.assertFalse(done)
def _opml(self, opml, urls, feed): for u in urls: HTTPretty.register_uri(HTTPretty.GET, u, body=feed, content_type='application/rss+xml') upload = Mock() upload.file = StringIO(opml) upload.filename = 'opml.xml' params = { 'opml': { 'upload': upload }, 'import': 'submit', '__formid__': 'form2', } request = testing.DummyRequest(post=params) response = view_feedadd(request) return response
def makeFakeGist(): gist = Mock() gist.description = "Test Gist #notebook #pandas #woo" gist.id = 123 # fake files filenames = ['a.ipynb', 'b.ipynb', 'test.txt'] files = {} for fn in filenames: fo = Mock() fo.filename = fn fo.content = fn+" content" files[fn] = fo gist.files = files # fake history history = [] dates = pd.date_range("2000", freq="D", periods=4).to_pydatetime() for i, date in enumerate(dates): state = Mock() state.version = i state.committed_at = date raw_data = {} files = {} for fn in filenames: fo = { 'content': "{fn}_{i}_revision_content".format(fn=fn, i=i), 'filename': fn, } files[fn] = fo # after 2, don't include 'a.ipynb' if i >= 2: del files['a.ipynb'] raw_data['files'] = files state.raw_data = raw_data history.append(state) gist.history = history return gist
def makeFakeGist(): gist = Mock() gist.description = "Test Gist #notebook #pandas #woo" gist.id = 123 # fake files filenames = ['a.ipynb', 'b.ipynb', 'test.txt'] files = {} for fn in filenames: fo = Mock() fo.filename = fn fo.content = fn + " content" files[fn] = fo gist.files = files # fake history history = [] dates = pd.date_range("2000", freq="D", periods=4).to_pydatetime() for i, date in enumerate(dates): state = Mock() state.version = i state.committed_at = date raw_data = {} files = {} for fn in filenames: fo = { 'content': "{fn}_{i}_revision_content".format(fn=fn, i=i), 'filename': fn, } files[fn] = fo # after 2, don't include 'a.ipynb' if i >= 2: del files['a.ipynb'] raw_data['files'] = files state.raw_data = raw_data history.append(state) gist.history = history return gist
def test_handles(self, mock_get_regex): match = Mock() mock_get_regex.return_value = Mock() mock_get_regex.return_value.match = match evt = Mock() evt.filename = "event.txt" if self.test_obj.__basenames__: match.return_value = False self.assertFalse(self.test_obj.handles(evt)) mock_get_regex.assert_called_with( [b for b in self.test_obj.__basenames__]) print("match calls: %s" % match.call_args_list) print("expected: %s" % [call(evt.filename) for b in self.test_obj.__basenames__]) match.assert_called_with(evt.filename) mock_get_regex.reset_mock() match.reset_mock() match.return_value = True self.assertTrue(self.test_obj.handles(evt)) match.assert_called_with(evt.filename) else: match.return_value = False self.assertFalse( self.test_obj.handles(evt, basename=os.path.basename(self.path))) mock_get_regex.assert_called_with([os.path.basename(self.path)]) match.assert_called_with(evt.filename) mock_get_regex.reset_mock() match.reset_mock() match.return_value = True self.assertTrue( self.test_obj.handles(evt, basename=os.path.basename(self.path))) mock_get_regex.assert_called_with([os.path.basename(self.path)]) match.assert_called_with(evt.filename)
def test_handle_event(self, mock_handlers): eset = self.get_obj() eset.entry_init = Mock() mock_handlers.return_value = [Mock(), Mock(), Mock()] for hdlr in mock_handlers.return_value: hdlr.__name__ = "handler" eset.entries = dict() def reset(): eset.entry_init.reset_mock() for hdlr in mock_handlers.return_value: hdlr.reset_mock() # test that a bogus deleted event is discarded evt = Mock() evt.code2str.return_value = "deleted" evt.filename = os.path.join(datastore, "test.txt") eset.handle_event(evt) self.assertFalse(eset.entry_init.called) self.assertItemsEqual(eset.entries, dict()) for hdlr in mock_handlers.return_value: self.assertFalse(hdlr.handles.called) self.assertFalse(hdlr.ignore.called) # test creation of a new file for action in ["exists", "created", "changed"]: evt = Mock() evt.code2str.return_value = action evt.filename = os.path.join(datastore, "test.txt") # test with no handler that handles for hdlr in mock_handlers.return_value: hdlr.handles.return_value = False hdlr.ignore.return_value = False reset() eset.handle_event(evt) self.assertFalse(eset.entry_init.called) self.assertItemsEqual(eset.entries, dict()) for hdlr in mock_handlers.return_value: hdlr.handles.assert_called_with(evt, basename=eset.path) hdlr.ignore.assert_called_with(evt, basename=eset.path) # test with a handler that handles the entry reset() mock_handlers.return_value[-1].handles.return_value = True eset.handle_event(evt) eset.entry_init.assert_called_with(evt, mock_handlers.return_value[-1]) for hdlr in mock_handlers.return_value: hdlr.handles.assert_called_with(evt, basename=eset.path) if not hdlr.return_value: hdlr.ignore.assert_called_with(evt, basename=eset.path) # test with a handler that ignores the entry before one # that handles it reset() mock_handlers.return_value[0].ignore.return_value = True eset.handle_event(evt) self.assertFalse(eset.entry_init.called) mock_handlers.return_value[0].handles.assert_called_with(evt, basename=eset.path) mock_handlers.return_value[0].ignore.assert_called_with(evt, basename=eset.path) for hdlr in mock_handlers.return_value[1:]: self.assertFalse(hdlr.handles.called) self.assertFalse(hdlr.ignore.called) # test changed event with an entry that already exists reset() evt = Mock() evt.code2str.return_value = "changed" evt.filename = os.path.join(datastore, "test.txt") eset.entries[evt.filename] = Mock() eset.handle_event(evt) self.assertFalse(eset.entry_init.called) for hdlr in mock_handlers.return_value: self.assertFalse(hdlr.handles.called) self.assertFalse(hdlr.ignore.called) eset.entries[evt.filename].handle_event.assert_called_with(evt) # test deleted event with an entry that already exists reset() evt.code2str.return_value = "deleted" eset.handle_event(evt) self.assertFalse(eset.entry_init.called) for hdlr in mock_handlers.return_value: self.assertFalse(hdlr.handles.called) self.assertFalse(hdlr.ignore.called) self.assertItemsEqual(eset.entries, dict())
def test_bad_zip(self, infolist): fake = Mock() fake.filename = '..' infolist.return_value = [fake] r = self.make_create_request(self.create_data) eq_(r.status_code, 400, r.content)
def test_process(self, mock_get_user, mock_get_commit, mock_commit_hunk_init, mock_put_multi, mock_get_repo, mock_commit_init): """Ensure process_commit saves a Commit and CommitHunks to the datastore. """ repo = repository.Repository(id=123, name='foo') mock_get_repo.return_value = repo mock_commit_init.get_by_id.return_value = None mock_author = Mock() mock_author.id = 900 mock_author.date = datetime.now() mock_author.name = 'Bruce Lee' mock_author.email = '*****@*****.**' mock_committer = Mock() mock_committer.id = 900 mock_committer.date = datetime.now() mock_committer.name = 'Bruce Lee' mock_committer.email = '*****@*****.**' mock_commit_prop = Mock() mock_commit_prop.author = mock_author mock_commit_prop.committer = mock_committer mock_commit_prop.message = 'blah' mock_commit = Mock() mock_commit.commit = mock_commit_prop file1 = Mock() file1.filename = 'file1.py' file1.patch = '@@ -0,0 +1,4 @@ def main(): \n\n' file2 = Mock() file2.filename = 'file2.py' file2.patch = '@@ -14,4 +14,3 @@ def foo(bar): \n\n' mock_commit.files = [file1, file2] mock_author_user = Mock() mock_author_user.id = '123' mock_commit.author = mock_author mock_commit.sha = 'abc' mock_committer_user = Mock() mock_committer_user.id = '123' mock_commit.committer = mock_committer mock_get_commit.return_value = mock_commit commit = Mock() commit.key = Mock() commit.author_date = mock_author.date mock_commit_init.return_value = commit owner_token = 'token' user = User(id=123) user.github_token = owner_token mock_get_user.return_value = user commit_hunks = [Mock(), Mock()] mock_commit_hunk_init.side_effect = commit_hunks repo_id = '123' commit_id = 'abc' repository.process_commit(repo_id, commit_id, user.key.id()) mock_get_repo.assert_called_once_with(repo_id) mock_commit_init.get_by_id.assert_called_once_with(commit_id, parent=repo.key) mock_get_commit.assert_called_once_with(repo.name, commit_id, owner_token) self.assertEqual([call(user.key.id()), call('github_%s' % mock_author.id), call('github_%s' % mock_committer.id)], mock_get_user.call_args_list) mock_commit_init.assert_called_once_with( id=commit_id, parent=repo.key, author=user.key, author_name=mock_author.name, author_email=mock_author.email, author_date=mock_author.date, committer=user.key, committer_name=mock_committer.name, committer_email=mock_committer.email, committer_date=mock_committer.date, message=mock_commit_prop.message ) mock_commit_init.return_value.put.assert_called_once_with() expected = [call(parent=commit.key, commit=commit.key, filename='file1.py', lines=[1, 2, 3, 4], timestamp=mock_author.date), call(parent=commit.key, commit=commit.key, filename='file2.py', lines=[14, 15, 16], timestamp=mock_author.date)] self.assertEqual(expected, mock_commit_hunk_init.call_args_list) mock_put_multi.assert_called_once_with(commit_hunks)
def setup_mock_options(cls, hosts=None, filename=None): mock_options = Mock() mock_options.hosts = hosts mock_options.filename = filename mock_options.verbosity = False return mock_options