Example #1
0
    def test_fsync(self):

        file = "/dir1/dir2/file"
        testfs = vofs.VOFS(self.testMountPoint, self.testCacheDir, opt)

        testfs.client = Object()
        node = Mock(spec=vos.Node)
        node.isdir = Mock(return_value=False)
        node.props = Object
        node.props.get = Mock(
            side_effect=SideEffect(
                {("islocked", False): False, ("length",): 10, ("MD5",): 12354}, name="node.props.get"
            )
        )
        node.type = "vos:DataNode"
        node.name = "testNode"
        testfs.client.get_node = Mock(return_value=node)
        with patch("vos.CadcCache.FileHandle") as mockFileHandle:
            mockFileHandle.return_value = MyFileHandle(file, testfs.cache, None)
            fh = testfs.open(file, os.O_RDWR | os.O_CREAT, None)
            HandleWrapper.file_handle(fh).cache_file_handle.fsync = Mock(
                wraps=HandleWrapper.file_handle(fh).cache_file_handle.fsync
            )
            testfs.fsync(file, False, fh)
            HandleWrapper.file_handle(fh).cache_file_handle.fsync.assert_called_once_with()
            HandleWrapper.file_handle(fh).cache_file_handle.fsync.assert_called_once_with()
    def test_onError(self, log):
        error = Mock()
        error.type = "test"
        e = self.plugin.onError(error, sentinel.anything)

        self.assertEquals(len(e["events"]), 1)
        self.assertEquals(e["events"][0]["severity"], ZenEventClasses.Error)
Example #3
0
    def test_anchor(self):
        target = Mock()
        target.type = "node"

        source = Mock()
        source.type = "node"

        relation = Mock()
        relation.type = "edge"

        # given two node objects connected by an edge object

        target.name = "target"
        source.name = "source"

        properties = {"source-object": "source", "target-object": "target"}

        def getitem(name):
            return properties[name]

        relation.__getitem__ = Mock(side_effect=getitem)
        relation.name = "relation"

        # added to diagram

        self.diagram.add(relation)
        self.diagram.add(target)
        self.diagram.add(source)

        # when anchors are set

        self.diagram.set_anchors()

        # each DrawableNode object should be referenced by proper DrawableEdge object's anchors
        drawable_relation = self.diagram.edges["relation"]
        drawable_source = self.diagram.nodes["source"]
        drawable_target = self.diagram.nodes["target"]

        self.assertEquals(drawable_source, drawable_relation.source_anchor.slot)
        self.assertEquals(drawable_target, drawable_relation.target_anchor.slot)

        # and each DrawableNode object's anchor should reference the
        # DrawableEdge object
        self.assertEquals(drawable_relation, drawable_source.anchors.pop().connector)
        self.assertEquals(drawable_relation, drawable_target.anchors.pop().connector)
    def test_populate_database_non_existent_model(self):
        # given
        item = Mock()
        item.type = "random"
        item.properties = [""]
        items = [item]

        # then
        with self.assertRaises(NonExistentModelException):
            populate_database(items)
Example #5
0
 def test_with_app(self):
     product = Mock()
     product.name = "Steamcube"
     product.id = 9999
     product.app_slug = "scube"
     product.type = amo.ADDON_WEBAPP
     s = render("""{{ hub_breadcrumbs(product) }}""", {"request": self.request, "product": product})
     crumbs = pq(s)("li")
     expected = [("My Submissions", reverse("mkt.developers.apps")), ("Steamcube", None)]
     amo.tests.check_links(expected, crumbs, verify=False)
Example #6
0
def test_tree_type_checker():
    # check that when TreeType.all, we accept all trees, w/o checking type
    tree_filter = tree_type_checker(TreeType.all)
    nt.ok_(tree_filter("fake_tree"))

    mock_tree = Mock()
    mock_tree.type = TreeType.axon

    # single arg
    tree_filter = tree_type_checker(TreeType.axon)
    nt.ok_(tree_filter(mock_tree))

    mock_tree.type = TreeType.basal_dendrite
    nt.ok_(not tree_filter(mock_tree))

    # multiple args
    tree_filter = tree_type_checker(TreeType.axon, TreeType.basal_dendrite)
    nt.ok_(tree_filter(mock_tree))

    tree_filter = tree_type_checker(*NEURITES)
    nt.ok_(tree_filter("fake_tree"))
    def test_populate_database_add_user(self):
        # given
        item = Mock()
        item.type = "user"
        item.properties = ["bob", "bob@bob.com", "bobpw"]
        items = [item]

        # when
        populate_database(items)

        # then
        self.assert_user_with_username_exists_in_database(item.properties[0])
    def test_populate_database_add_project(self):
        # given
        item = Mock()
        item.type = "project"
        item.properties = ["title", "filename", "techno", "url", 1]
        items = [item]

        # when
        populate_database(items)

        # then
        self.assert_project_with_title_exists_in_database(item.properties[0])
    def test_populate_database_add_post(self):
        # given
        item = Mock()
        item.type = "post"
        item.properties = ["title", "filename", datetime.now(), "category", "author"]
        items = [item]

        # when
        populate_database(items)

        # then
        self.assert_post_with_title_exists_in_database(item.properties[0])
    def test_populate_database_add_status(self):
        # given
        item = Mock()
        item.type = "status"
        item.properties = ["status_txt"]
        items = [item]

        # when
        populate_database(items)

        # then
        self.assert_status_with_name_exists_in_database(item.properties[0])
    def test_populate_database_add_technology(self):
        # given
        item = Mock()
        item.type = "technology"
        item.properties = ["techno_txt"]
        items = [item]

        # when
        populate_database(items)

        # then
        self.assert_technology_with_name_exists_in_database(item.properties[0])
    def test_exercise_sell(self):
        order = Mock()
        order.type = "sell"
        order.bond_amount = 156
        self.mock_create.return_value = ["123"]

        confirmation_obj = self.trade_service.exercise(order)

        self.mock_create.assert_called_once_with(order)
        self.mock_ionobj.assert_called_once_with(
            "Confirmation", status="complete", tracking_number="123", proceeds=156 * 1.56
        )
        self.assertTrue(confirmation_obj is self.mock_ionobj.return_value)
Example #13
0
 def test_with_app(self):
     addon = Mock()
     addon.name = "Firebug"
     addon.id = 1843
     addon.app_slug = "fbug"
     addon.type = amo.ADDON_WEBAPP
     s = render("""{{ hub_breadcrumbs(addon) }}""", {"request": self.request, "addon": addon})
     doc = pq(s)
     crumbs = doc("li")
     eq_(crumbs.eq(0).text(), "My Submissions")
     eq_(crumbs.eq(0).children("a").attr("href"), reverse("mkt.developers.apps"))
     eq_(crumbs.eq(1).text(), "Firebug")
     eq_(crumbs.eq(1).children("a"), [])
Example #14
0
    def test_fsync2(self):
        file = "/dir1/dir2/file"
        testfs = vofs.VOFS(self.testMountPoint, self.testCacheDir, opt)

        testfs.client = Object()
        node = Mock(spec=vos.Node)
        node.isdir = Mock(return_value=False)
        node.props = Object
        node.props.get = Mock(
            side_effect=SideEffect(
                {("islocked", False): False, ("length",): 10, ("MD5",): 12354}, name="node.props.get"
            )
        )
        node.type = "vos:DataNode"
        testfs.client.get_node = Mock(return_value=node)
        # Try flushing on a read-only file.
        with patch("vos.CadcCache.FileHandle") as mockFileHandle:
            mockFileHandle.return_value = MyFileHandle(file, testfs.cache, None)
            fh = testfs.open(file, os.O_RDONLY, None)
            self.assertFalse(HandleWrapper.file_handle(fh).cache_file_handle.fileModified)
            HandleWrapper.file_handle(fh).cache_file_handle.fsync = Mock(
                wraps=HandleWrapper.file_handle(fh).cache_file_handle.fsync
            )
            with self.assertRaises(FuseOSError) as e:
                testfs.fsync(file, False, fh)
            self.assertEqual(e.exception.errno, EPERM)
            self.assertEqual(HandleWrapper.file_handle(fh).cache_file_handle.fsync.call_count, 0)
            self.assertFalse(HandleWrapper.file_handle(fh).cache_file_handle.fileModified)

            testfs.release(file, fh)

        # Try with an invalid file descriptor
        with self.assertRaises(FuseOSError) as e:
            testfs.fsync(file, False, -1)
        self.assertEqual(e.exception.errno, EIO)

        # Try flushing on a read-only file system.
        with patch("vos.CadcCache.FileHandle") as mockFileHandle:
            myopt = copy.copy(opt)
            testfs = vofs.VOFS(self.testMountPoint, self.testCacheDir, myopt)
            mockFileHandle.return_value = MyFileHandle(file, testfs.cache, None)
            myopt.readonly = True
            testfs.client = Object()
            testfs.client.get_node = Mock(return_value=node)
            fh = testfs.open(file, os.O_RDONLY, None)
            HandleWrapper.file_handle(fh).cache_file_handle.fsync = Mock(
                wraps=HandleWrapper.file_handle(fh).cache_file_handle.fsync
            )
            testfs.fsync(file, False, fh)
            self.assertEqual(HandleWrapper.file_handle(fh).cache_file_handle.fsync.call_count, 0)
            testfs.release(file, fh)
Example #15
0
    def newDevice(self, *args, **kwargs):
        """ Return a new Device instance suitable for testing. """
        device_class = kwargs.pop("device_class")
        exists = kwargs.pop("exists", False)
        part_type = kwargs.pop("part_type", parted.PARTITION_NORMAL)
        device = device_class(*args, **kwargs)

        if exists:
            # set up mock parted.Device w/ correct size
            device._partedDevice = Mock()
            device._partedDevice.getLength = Mock(return_value=int(device.size.convertTo(spec="B")))
            device._partedDevice.sectorSize = 512

        if isinstance(device, blivet.devices.PartitionDevice):
            # if exists:
            #    device.parents = device.req_disks
            device.parents = device.req_disks

            partedPartition = Mock()

            if device.disk:
                part_num = device.name[len(device.disk.name) :].split("p")[-1]
                partedPartition.number = int(part_num)

            partedPartition.type = part_type
            partedPartition.path = device.path
            partedPartition.getDeviceNodeName = Mock(return_value=device.name)
            if len(device.parents) == 1:
                disk_name = device.parents[0].name
                number = device.name.replace(disk_name, "")
                try:
                    partedPartition.number = int(number)
                except ValueError:
                    pass

            device._partedPartition = partedPartition
        elif isinstance(device, blivet.devices.LVMVolumeGroupDevice) and exists:
            device._complete = True

        device.exists = exists
        device.format.exists = exists

        if isinstance(device, blivet.devices.PartitionDevice):
            # PartitionDevice.probe sets up data needed for resize operations
            device.probe()

        return device
    def test_znode_watch_triggered_for_deleted_znode_causes_wait_for_it_to_exist(self):
        mock_zk = _mock_zk()

        # we're asserting on the side effects of creating the group
        ActiveKazooGroup(mock_zk, DEFAULT_PATH)

        assert mock_zk.exists_async.call_count == 0

        _, watch_callback = mock_zk.get_children_async.call_args[0]

        mock_watch_event = Mock()
        mock_watch_event.state = KeeperState.CONNECTED
        mock_watch_event.type = EventType.DELETED

        watch_callback(mock_watch_event)

        assert mock_zk.exists_async.call_count == 1
    def test_znode_watch_triggered_for_child_events_causes_reprocess(self):
        mock_zk = _mock_zk()

        # we're asserting on the side effects of creating the group
        ActiveKazooGroup(mock_zk, DEFAULT_PATH)

        assert mock_zk.get_children_async.call_count == 1

        _, watch_callback = mock_zk.get_children_async.call_args[0]

        mock_watch_event = Mock()
        mock_watch_event.state = KeeperState.CONNECTED
        mock_watch_event.type = EventType.CHILD

        watch_callback(mock_watch_event)

        assert mock_zk.get_children_async.call_count == 2
    def test_exercise_buy(self):
        # set up order
        order = Mock()
        order.type = "buy"
        order.cash_amount = 156
        self.mock_create.return_value = ["111"]

        # TEST: Execute the service operation call
        confirmation_obj = self.trade_service.exercise(order)

        # How is the test result
        # assert resource_registry.create did get called with correct
        # arguments
        self.mock_create.assert_called_once_with(order)
        # assert mock ion object is called
        self.mock_ionobj.assert_called_once_with(
            "Confirmation", status="complete", tracking_number="111", proceeds=156 / 1.56
        )
        self.assertTrue(confirmation_obj is self.mock_ionobj.return_value)
Example #19
0
    def test_get_payload_ignores_registration(self, Dhis2SettingsPatch, cases_referenced_by_xform, push_case):

        """
        get_payload should raise IgnoreDocument given a registration form
        """
        case_mock = Mock()
        case_mock.type = CASE_TYPE
        cases_referenced_by_xform.return_value = [case_mock]

        class Settings(object):
            dhis2 = {"host": "foo", "username": "foo", "password": "foo", "top_org_unit_name": "foo"}

        Dhis2SettingsPatch.for_domain.return_value = Settings()

        form_mock = MagicMock()
        form_mock.__getitem__.return_value = REGISTER_CHILD_XMLNS

        payload_generator = FormRepeaterDhis2EventPayloadGenerator(None)
        with self.assertRaises(IgnoreDocument):
            payload_generator.get_payload(None, form_mock)
Example #20
0
 def test_with_app_and_items(self):
     product = Mock()
     product.name = "Steamcube"
     product.id = 9999
     product.app_slug = "scube"
     product.type = amo.ADDON_WEBAPP
     product.get_dev_url.return_value = reverse("mkt.developers.apps.edit", args=[product.app_slug])
     s = render(
         """{{ hub_breadcrumbs(product,
                                      items=[('/foo', 'foo'),
                                             ('/bar', 'bar')]) }}""",
         {"request": self.request, "product": product},
     )
     crumbs = pq(s)("li")
     expected = [
         ("My Submissions", reverse("mkt.developers.apps")),
         ("Steamcube", product.get_dev_url()),
         ("foo", "/foo"),
         ("bar", "/bar"),
     ]
     amo.tests.check_links(expected, crumbs, verify=False)
Example #21
0
    def getDisk(self, disk_type, primary_count=0, has_extended=False, logical_count=0):
        """ Return a mock representing a parted.Disk. """
        disk = Mock()

        disk.type = disk_type
        label_type_info = disklabel_types[disk_type]
        (max_primaries, supports_extended, max_logicals) = label_type_info

        # primary partitions
        disk.primaryPartitionCount = primary_count
        disk.maxPrimaryPartitionCount = max_primaries

        # extended partitions
        disk.supportsFeature = Mock(return_value=supports_extended)
        disk.getExtendedPartition = Mock(return_value=has_extended)

        # logical partitions
        disk.getMaxLogicalPartitions = Mock(return_value=max_logicals)
        disk.getLogicalPartitions = Mock(return_value=[0] * logical_count)

        return disk
    def newDevice(*args, **kwargs):
        """ Return a new Device instance suitable for testing. """
        args = args[1:]  # drop self arg
        device_class = kwargs.pop("device_class")
        exists = kwargs.pop("exists", False)
        part_type = kwargs.pop("part_type", parted.PARTITION_NORMAL)
        device = device_class(*args, **kwargs)

        if exists:
            # set up mock parted.Device w/ correct size
            device._partedDevice = Mock()
            device._partedDevice.getSize = Mock(return_value=float(device.size))
            device._partedDevice.sectorSize = 512

        if isinstance(device, pyanaconda.storage.devices.PartitionDevice):
            # if exists:
            #    device.parents = device.req_disks
            device.parents = device.req_disks

            partedPartition = Mock()

            if device.disk:
                part_num = device.name[len(device.disk.name) :].split("p")[-1]
                partedPartition.number = int(part_num)

            partedPartition.type = part_type
            partedPartition.path = device.path
            partedPartition.getDeviceNodeName = Mock(return_value=device.name)
            partedPartition.getSize = Mock(return_value=float(device.size))
            device._partedPartition = partedPartition

        device.exists = exists
        device.format.exists = exists

        if isinstance(device, pyanaconda.storage.devices.PartitionDevice):
            # PartitionDevice.probe sets up data needed for resize operations
            device.probe()

        return device
Example #23
0
 def test_with_addon_and_items(self):
     addon = Mock()
     addon.name = "Firebug"
     addon.id = 1843
     addon.app_slug = "fbug"
     addon.type = amo.ADDON_WEBAPP
     addon.get_dev_url.return_value = reverse("mkt.developers.apps.edit", args=[addon.app_slug])
     s = render(
         """{{ hub_breadcrumbs(addon,
                                      items=[('/foo', 'foo'),
                                             ('/bar', 'bar')]) }}""",
         {"request": self.request, "addon": addon},
     )
     doc = pq(s)
     crumbs = doc("li")
     eq_(len(crumbs), 4)
     eq_(crumbs.eq(1).text(), "Firebug")
     eq_(crumbs.eq(1).children("a").attr("href"), addon.get_dev_url())
     eq_(crumbs.eq(2).text(), "foo")
     eq_(crumbs.eq(2).children("a").attr("href"), "/foo")
     eq_(crumbs.eq(3).text(), "bar")
     eq_(crumbs.eq(3).children("a").attr("href"), "/bar")
Example #24
0
 def generate_python_sys_libs(self):
     cell_mock = Mock()
     cell_mock.type = BiiType(PYTHON)
     validator = getSystemNameValidatorFor(cell_mock).names()
     return validator
Example #25
0
 def create_mock_service(self, service_type, signature_version="v2"):
     service = Mock()
     service.type = service_type
     service.signature_version = signature_version
     return service
Example #26
0
 def create_mock_plugin(tab_type, priority):
     """ Create a mock plugin with the specified name and priority. """
     mock_plugin = Mock()
     mock_plugin.type = tab_type
     mock_plugin.priority = priority
     return mock_plugin
Example #27
0
 def test_is_passable_with_no_passable_tiles(self):
     tile = Mock()
     tile.type = "type"
     self.assertTrue(not self.unit.is_passable(tile))
Example #28
0
 def test_is_passable_with_a_unpassable_tile(self):
     tile = Mock()
     tile.type = "type"
     self.unit.passable_tile_types.append("nope")
     self.assertTrue(not self.unit.is_passable(tile))
Example #29
0
    def test_truncate(self):
        callCount = [0]

        def mock_read(block_size):
            callCount[0] += 1
            if callCount[0] == 1:
                return "1234"
            else:
                return None

        file = "/dir1/dir2/file"
        testfs = vofs.VOFS(self.testMountPoint, self.testCacheDir, opt)
        node = Mock(spec=vos.Node)
        node.isdir = Mock(return_value=False)
        node.props = Object
        node.props.get = Mock(
            side_effect=SideEffect(
                {("islocked", False): False, ("length",): 10, ("MD5",): 12354}, name="node.props.get"
            )
        )
        node.type = "vos:DataNode"
        node.uri = "vos:/dir1/dir2/file"
        node.name = "testNode"
        testfs.client = Object()
        testfs.client.get_node = Mock(return_value=node)
        testfs.client.close = Mock()
        testfs.client.read = Mock(side_effect=mock_read)
        testfs.client.copy = Mock()
        vos_VOFILE = Object()
        vos_VOFILE.close = Mock()
        vos_VOFILE.read = Mock(side_effect=mock_read)
        testfs.client.open = Mock(return_value=vos_VOFILE)
        testfs.client.nodeCache = Object()
        testfs.client.nodeCache = NodeCache()

        # Truncate a non-open file to 0 bytes
        testfs.cache.open = Mock(wraps=testfs.cache.open)
        origRelease = FileHandle.release
        origTruncate = FileHandle.truncate
        with nested(patch("vos.CadcCache.FileHandle.release"), patch("vos.CadcCache.FileHandle")) as (
            mockRelease,
            mockFileHandle,
        ):
            mockFileHandle.return_value = MyFileHandle(file, testfs.cache, None)
            mockFileHandle.return_value.readData = Mock(wraps=mockFileHandle.return_value.readData)
            mockRelease.wraps = origRelease  # TODO This doesn't really work,
            # release is not called and so open
            # files are being leaked
            testfs.truncate(file, 0)
            self.assertEqual(testfs.cache.open.call_count, 1)
            self.assertEqual(testfs.cache.open.call_args[0][0], file)
            self.assertFalse(testfs.cache.open.call_args[0][1])
            self.assertTrue(testfs.cache.open.call_args[0][2])
            mockRelease.assert_called_once_with()
            self.assertEqual(mockFileHandle.return_value.readData.call_count, 1)

        # Truncate a non-open file past the start of the file.
        testfs.cache.open.reset_mock()
        with nested(patch("vos.CadcCache.FileHandle.release"), patch("vos.CadcCache.FileHandle.readData")) as mocks:
            mockRelease = mocks[0]
            mockReadData = mocks[1]
            mockRelease.wraps = origRelease  # TODO This doesn't really work,
            # release is not called and so open
            # files are being leaked
            with patch("vos.CadcCache.FileHandle.truncate") as mockTruncate:
                mockTruncate.wraps = origTruncate  # TODO Same issue as the
                # mockRelease TODO above.
                testfs.truncate(file, 5)
                self.assertEqual(testfs.cache.open.call_args[0][0], file)
                self.assertFalse(testfs.cache.open.call_args[0][1])
                mockTruncate.assert_called_once_with(5)
            mockRelease.assert_called_once_with()

        # Truncate with an exception returned by the CadcCache truncate
        testfs.cache.open.reset_mock()
        with nested(patch("vos.CadcCache.FileHandle.release"), patch("vos.CadcCache.FileHandle.readData")) as mocks:
            mockRelease = mocks[0]
            mockReadData = mocks[1]
            mockRelease.wraps = origRelease  # TODO This doesn't really work,
            # release is not called and so open
            # files are being leaked
            with patch("vos.CadcCache.FileHandle.truncate") as mockTruncate:
                mockTruncate.side_effect = NotImplementedError("an error")
                with self.assertRaises(NotImplementedError):
                    testfs.truncate(file, 5)
                self.assertEqual(testfs.cache.open.call_args[0][0], file)
                self.assertFalse(testfs.cache.open.call_args[0][1])
            mockRelease.assert_called_once_with()

        # Truncate an already opened file given the file handle.
        with nested(patch("vos.CadcCache.FileHandle.release"), patch("vos.CadcCache.FileHandle.readData")) as mocks:
            mockRelease = mocks[0]
            mockReadData = mocks[1]
            mockRelease.wraps = origRelease  # TODO This doesn't really work,
            # release is not called and so open
            # files are being leaked
            try:
                fh = testfs.open(file, os.O_RDWR | os.O_CREAT, None)
                testfs.cache.open.reset_mock()
                with patch("vos.CadcCache.FileHandle.truncate") as mockTruncate:
                    mockTruncate.wraps = origTruncate  # TODO Same issue as the
                    # mockRelease TODO above.
                    testfs.truncate(file, 20, fh)
                    # Open and release should not be called, truncate should be
                    # called.
                    self.assertEqual(testfs.cache.open.call_count, 0)
                    mockTruncate.assert_called_once_with(20)
                self.assertEqual(mockRelease.call_count, 0)
            finally:
                testfs.release(file, fh)

        # Create a new file system for testing. This is required because of the
        # leaked file handles from the previous tests.

        testfs2 = vofs.VOFS(self.testMountPoint, self.testCacheDir, opt)
        testfs2.client = testfs.client
        testfs = None
        testfs2.cache.open = Mock(wraps=testfs2.cache.open)

        # Truncate a read only file handle.
        with nested(patch("vos.CadcCache.FileHandle.release"), patch("vos.CadcCache.FileHandle")) as (
            mockRelease,
            mockFileHandle,
        ):
            mockRelease.wraps = origRelease
            mockFileHandle.return_value = MyFileHandle(file, testfs2.cache, None)
            mockFileHandle.return_value.readData = Mock(wraps=mockFileHandle.return_value.readData)
            try:
                fh = testfs2.open(file, os.O_RDONLY, None)
                testfs2.cache.open.reset_mock()
                with patch("vos.CadcCache.FileHandle.truncate") as mockTruncate:
                    mockTruncate.wraps = origTruncate
                    with self.assertRaises(FuseOSError):
                        testfs2.truncate(file, 20, fh)
                    # Open, release and truncate should not be called.
                    self.assertEqual(testfs2.cache.open.call_count, 0)
                    self.assertEqual(mockTruncate.call_count, 0)
                self.assertEqual(mockRelease.call_count, 0)
            finally:
                testfs2.release(file, fh)

        # Truncate with an invalid file descriptor.
        with self.assertRaises(KeyError) as e:
            testfs2.truncate(file, 20, -1)