Example #1
0
    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)
Example #2
0
    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))
Example #3
0
    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)
Example #4
0
    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 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 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
Example #7
0
    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)
Example #8
0
 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()
Example #9
0
    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)
Example #10
0
 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
Example #11
0
 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
Example #12
0
 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_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)
Example #14
0
        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 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
Example #16
0
    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)
Example #17
0
    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_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)
Example #19
0
    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)
Example #20
0
    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)
Example #21
0
    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)
Example #22
0
    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)
Example #23
0
File: common.py Project: pjc42/nbx
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
Example #24
0
    def test_handle_event(self):
        eset = self.get_obj()
        eset.entry_init = Mock()
        eset._handlers = [Mock(), Mock(), Mock()]
        for hdlr in eset.handlers:
            hdlr.__name__ = "handler"
        eset.entries = dict()

        def reset():
            eset.entry_init.reset_mock()
            for hdlr in eset.handlers:
                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 eset.handlers:
            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 eset.handlers:
                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 eset.handlers:
                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()
            eset.handlers[-1].handles.return_value = True
            eset.handle_event(evt)
            eset.entry_init.assert_called_with(evt, eset.handlers[-1])
            for hdlr in eset.handlers:
                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()
            eset.handlers[0].ignore.return_value = True
            eset.handle_event(evt)
            self.assertFalse(eset.entry_init.called)
            eset.handlers[0].handles.assert_called_with(evt, basename=eset.path)
            eset.handlers[0].ignore.assert_called_with(evt, basename=eset.path)
            for hdlr in eset.handlers[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 eset.handlers:
            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 eset.handlers:
            self.assertFalse(hdlr.handles.called)
            self.assertFalse(hdlr.ignore.called)
        self.assertItemsEqual(eset.entries, dict())
Example #25
0
 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 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