def test_should_not_include_files_outside_config_directory(self):

        mock_svn_service = Mock(SvnService)
        mock_svn_service.config_url = "svn://url/for/configuration/repository"
        mock_svn_service.path_to_config = "/config"
        mock_svn_service.client = Mock()
        mock_info = Mock()

        mock_path_object_1 = Mock()
        mock_path_object_1.path = "/config/foo"
        mock_path_object_1.action = "A"

        mock_path_object_2 = Mock()
        mock_path_object_2.path = "/XXXXXX/bar"
        mock_path_object_2.action = "A"

        mock_path_object_3 = Mock()
        mock_path_object_3.path = "/XXX/foobar"
        mock_path_object_3.action = "A"

        mock_info.changed_paths = [mock_path_object_1, mock_path_object_2, mock_path_object_3]
        mock_svn_service.get_logs_for_revision.return_value = [mock_info]

        actual = SvnService.get_changed_paths_with_action(mock_svn_service, "1980")

        self.assertEqual([("foo", "A")], actual)
Example #2
0
 def test_remove_duplicates(self):
     self.assertEqual([], remove_duplicates([]))
     issue1 = Mock()
     issue2 = Mock()
     issue1.path = "/filename"
     issue2.path = "/filename"
     issue1.severity = 10
     issue2.severity = 10
     issue1.line_number_start = None
     issue2.line_number_start = None
     issue1.line_position = None
     issue2.line_position = None
     issue1.message = "foo"
     issue2.message = "bar"
     self.assertEqual([issue1, issue2], remove_duplicates([issue1, issue2]))
     issue1.line_number_start = 42
     issue2.line_number_start = 42
     issue1.message = "line too long"
     issue2.message = "unused import foo"
     self.assertEqual([issue1, issue2], remove_duplicates([issue1, issue2]))
     issue1.line_number_start = 42
     issue2.line_number_start = 42
     issue1.line_position = -1
     issue2.line_position = -1
     issue1.message = "unused import bar"
     issue2.message = "module bar not used"
     self.assertEqual([issue1], remove_duplicates([issue1, issue2]))
     issue1.line_number_start = 42
     issue2.line_number_start = 42
     issue1.line_position = 12
     issue2.line_position = 28
     issue1.message = "unused import bar"
     issue2.message = "module foo not used"
     self.assertEqual([issue1, issue2], remove_duplicates([issue1, issue2]))
     issue1.line_number_start = 32
     issue2.line_number_start = 32
     issue1.line_position = 80
     issue2.line_position = -1
     issue1.message = "line too long (92 characters)"
     issue2.message = "Line too long (92/80)"
     self.assertEqual([issue1], remove_duplicates([issue1, issue2]))
     issue1.line_number_start = 32
     issue2.line_number_start = 33
     issue1.line_position = 80
     issue2.line_position = -1
     issue1.message = "line too long (92 characters)"
     issue2.message = "Line too long (92/80)"
     self.assertEqual([issue1, issue2], remove_duplicates([issue1, issue2]))
Example #3
0
    def test_create_auth_handler(self):
        """
        AuthorizationCodeGrant() should return a new instance of AuthorizationCodeAuthHandler on request
        """
        default_scope = "default_scope"
        scopes = ["first", "second"]
        path = "/auth"

        request_mock = Mock(spec=Request)
        request_mock.path = path
        request_mock.get_param.return_value = "code"

        scope_mock = Mock(Scope)

        server_mock = Mock()
        server_mock.authorize_path = path
        server_mock.auth_code_store = Mock()
        server_mock.client_store = Mock()
        server_mock.site_adapter = Mock()
        server_mock.token_generator = Mock()

        factory = AuthorizationCodeGrant(default_scope=default_scope, scopes=scopes, scope_class=scope_mock)
        result_class = factory(request_mock, server_mock)

        request_mock.get_param.assert_called_with("response_type")
        scope_mock.assert_called_with(default=default_scope, available=scopes)
        self.assertTrue(isinstance(result_class, AuthorizationCodeAuthHandler))
Example #4
0
    def test_owner_or_mod_required_passes_url_parameters(self):
        @owner_or_moderator_required
        def mock_view(request, user, context):
            return None

        request = Mock(spec=("path", "REQUEST", "user"))
        request.user = AnonymousUser()
        request.REQUEST = {"abra": "cadabra", "foo": "bar"}
        request.path = "/some/path/"
        user = self.create_user("user")
        response = mock_view(request, user, {})
        self.assertEqual(isinstance(response, HttpResponseRedirect), True)

        url = response["location"]
        parsed_url = urlparse(url)

        self.assertEqual(parsed_url.path, reverse("user_signin"))

        next = dict(parse_qsl(parsed_url.query))["next"]
        next_url = unquote(next)
        parsed_url = urlparse(next_url)

        self.assertEqual(parsed_url.path, request.path)

        query = dict(parse_qsl(parsed_url.query))
        self.assertEqual(set(query.keys()), set(["foo", "abra"]))
        self.assertEqual(set(query.values()), set(["bar", "cadabra"]))
        self.assertEqual(query["abra"], "cadabra")
Example #5
0
def test_api_resource():
    """
    Test APIResource class
    """
    resource = pdrest.APIResource()
    resource.register("method", "method", do_nothing)

    request = Mock()

    request.method = "method"
    request.path = "method"
    result = resource._get_callback(request)
    assert result[0] == do_nothing

    resource.getChild("method", request)

    resource.unregister(regex="method")

    # After unregister, the callback should be gone.
    result = resource._get_callback(request)
    assert result[0] is None

    resource.getChild("method", request)

    resource.children = Mock(name="what")
    result = resource.getChild("method", request)
    resource.getChild("method", request)
Example #6
0
 def create_mock_text_editor(content):
     """
     :param str content: Fake edits to return
     """
     mock = Mock(spec=TextEditor)
     mock.edit.return_value = content
     mock.path = None
     return mock
 def create_mock(name, build_depends, run_depends, path):
     m = Mock()
     m.name = name
     m.build_depends = build_depends
     m.buildtool_depends = []
     m.run_depends = run_depends
     m.exports = []
     m.path = path
     return m
 def create_mock(name, builddeps, path):
     m = Mock()
     m.name = name
     m.builddeps = builddeps
     m.buildtooldeps = []
     m.rundeps = []
     m.exports = []
     m.path = path
     return m
 def test_max_request(self):
     SilkyConfig().SILKY_MAX_REQUEST_BODY_SIZE = 10  # 10kb
     mock_request = Mock()
     mock_request.META = {"CONTENT_TYPE": "text/plain"}
     mock_request.GET = {}
     mock_request.body = "a".encode("ascii") * 1024 * 100  # 100kb
     mock_request.path = reverse("silk:requests")
     request_model = RequestModelFactory(mock_request).construct_request_model()
     self.assertFalse(request_model.raw_body)
 def test_user_access_to_page_with_group(self):
     """
     Test that method 'process_request' of PageAuthMiddleware middleware
     return None if user of request is a django user member of group
     associated with the page of the request
     """
     mock_request = Mock()
     mock_request.user = self.app_operator
     mock_request.path = self.pages_with_group[0].slug
     self.assertIsNone(self.middlware.process_request(mock_request))
 def test_user_access_to_page_without_group(self):
     """
     Test that method 'process_request' of PageAuthMiddleware middleware
     return None (page is accessible) if user of request is a django user
     and the request page don't have groups associated.
     """
     mock_request = Mock()
     mock_request.user = self.app_operator
     mock_request.path = self.pages_no_group[0].slug
     self.assertIsNone(self.middlware.process_request(mock_request))
 def test_anonymous_user_access_to_page_with_group(self):
     """
     Test that method 'process_request' of PageAuthMiddleware middleware
     return None if user of request is an 'AnonymousUser' and the request
     page have groups associated.
     """
     mock_request = Mock()
     mock_request.user = AnonymousUser()
     mock_request.path = self.pages_with_group[0].slug
     self.assertIsInstance(self.middlware.process_request(mock_request), HttpResponseForbidden)
 def test_user_access_to_page_with_other_group(self):
     """
     Test that method 'process_request' of PageAuthMiddleware middleware
     return an HttpResponseForbidden object if user of request is a django
     user who is not a member of group associated with the page of the
     request
     """
     mock_request = Mock()
     mock_request.user = self.app_admin
     mock_request.path = self.pages_with_group[0].slug
     self.assertIsInstance(self.middlware.process_request(mock_request), HttpResponseForbidden)
    def test_should_return_list_with_directory_name_and_action_for_path_to_file_when_a_file_has_been_added(self):

        mock_svn_service = Mock(SvnService)
        mock_svn_service.config_url = "svn://url/for/configuration/repository"
        mock_svn_service.path_to_config = "/config"
        mock_svn_service.client = Mock()
        mock_info = Mock()
        mock_path_object_1 = Mock()
        mock_path_object_1.path = "/config/"
        mock_path_object_1.action = "A"
        mock_info.changed_paths = [mock_path_object_1]
        mock_path_object_2 = Mock()
        mock_path_object_2.path = "/config/spam.egg"
        mock_path_object_2.action = "A"
        mock_info.changed_paths = [mock_path_object_1, mock_path_object_2]
        mock_svn_service.get_logs_for_revision.return_value = [mock_info]

        actual = SvnService.get_changed_paths_with_action(mock_svn_service, "1980")

        self.assertEqual([("", "A"), ("spam.egg", "A")], actual)
    def test_FilePathBaseBarFile_Base(self):
        # stub the files method to return a stub file
        stub_file = Mock(name="file")
        stub_torrent_handle = Mock(name="handle")
        stub_torrent_handle.get_torrent_info().files = Mock(return_value=[stub_file])

        # stub out file path to return the desired path
        stub_file.path = "base/file"

        handle = DownloadHandle(None, stub_torrent_handle)

        assert handle.basename == "base"
    def _test_syncdb_ok_scenario(self, args, db_command, comp_root, listdir=None, isdir=None, call_cmd=None):
        """This method provides a template for syncdb success scenario."""

        folders_visited = []
        files_visited = []
        cmd_executed = []

        main_folders = ["sql", "test_script.sql"]
        sql_content = ["module_setup.sql", "create_data.sql"]

        listdir = listdir or self._mock_list_dir(folders_visited, main_folders, sql_content)
        isdir = isdir or self._mock_isdir(files_visited)
        call_cmd = call_cmd or (lambda cmd: self._mock_callcmd(cmd, cmd_executed))

        def get(name):
            self.assertEqual(name, "database_config")

            return {
                "username": "test_user",
                "password": "12345",
                "port": 3306,
                "host": "localhost",
                "database": "testdb",
            }

        settings_facade = Mock()
        settings_facade.get = get
        settings_facade_cls = Mock(return_value=settings_facade)

        mock_os = Mock()

        mock_os.listdir = listdir
        mock_os.path = Mock(return_value=mock_os)
        mock_os.path.isdir = isdir

        cmd = SdkCommandSyncDb(args, cmd_factory=Mock(), settings_facade_cls=settings_facade_cls)
        cmd.exec_command(os_lib=mock_os, call_cmd=call_cmd)

        self.assertTrue(comp_root in folders_visited)
        self.assertTrue("%s/sql" % comp_root in folders_visited)
        self.assertTrue("%s/sql/module_setup.sql" % comp_root in files_visited)
        self.assertTrue("%s/sql/create_data.sql" % comp_root in files_visited)

        expected_cmds = [
            "%s --user=test_user --password=12345 -h localhost --database=testdb --port=3306 -e source samples/sql/module_setup.sql"
            % db_command,
            "%s --user=test_user --password=12345 -h localhost --database=testdb --port=3306 -e source samples/sql/create_data.sql"
            % db_command,
        ]

        for cmd in expected_cmds:
            self.assertTrue(cmd in cmd_executed)
    def test_should_return_list_with_tuples_including_one_tuple_which_has_a_delete_action(self):

        mock_svn_service = Mock(SvnService)
        mock_svn_service.config_url = "svn://url/for/configuration/repository"
        mock_svn_service.path_to_config = "/config"
        mock_svn_service.client = Mock()
        mock_info = Mock()
        mock_path_object_1 = Mock()
        mock_path_object_1.path = "/config/"
        mock_path_object_1.action = "A"
        mock_info.changed_paths = [mock_path_object_1]
        mock_path_object_2 = Mock()
        mock_path_object_2.path = "/config/spam.egg"
        mock_path_object_2.action = "A"
        mock_path_object_3 = Mock()
        mock_path_object_3.path = "/config/foo.bar"
        mock_path_object_3.action = "D"
        mock_info.changed_paths = [mock_path_object_1, mock_path_object_2, mock_path_object_3]
        mock_svn_service.get_logs_for_revision.return_value = [mock_info]

        actual = SvnService.get_changed_paths_with_action(mock_svn_service, "1980")

        self.assertEqual([("", "A"), ("spam.egg", "A"), ("foo.bar", "D")], actual)
Example #18
0
    def test_exec_add(self):
        """Test workspace add execution."""
        ws = Mock()
        ws.add = Mock()

        args = Mock()
        args.workspace_subcommand = "add"
        args.name = "foo"
        args.path = "/foo"

        self.subcommand.ws = ws
        self.subcommand.execute(args)

        ws.add.assert_called_with("foo", "/foo")
Example #19
0
 def test_img_404_warm_cache(self):
     """
     Ensure we go straight to a 404 response without setting anything new in
     cache or touching filesystem if we encounter a cached 404.
     """
     req = Mock()
     req.path = "/lt_cache/thumbnail/48/i/p.jpg"
     self.renderer._render_and_save = Mock()
     with patch("lazythumbs.views.cache", self.mc_factory(1)) as mc:
         resp = self.renderer.get(req, "thumbnail", "48", "i/p")
     self.assertEqual(resp.status_code, 404)
     self.assertEqual(resp["Content-Type"], "image/jpeg")
     self.assertTrue("Cache-Control" in resp)
     self.assertFalse(mc.set.called)
Example #20
0
 def test_no_img_should_404(self):
     """
     When save fails with EEXIST error, it will try to read the file again
     But if it still can't be read, make sure it returns a 404 instead of 0-byte image.
     """
     req = Mock()
     req.path = "/lt_cache/thumbnail/48/i/p.jpg"
     self.renderer.fs.save = Mock()
     err = OSError()
     err.errno = errno.EEXIST
     self.renderer.fs.save.side_effect = err
     with patch("lazythumbs.views.Image", self.mock_Image):
         with patch("lazythumbs.views.cache", MockCache()):
             resp = self.renderer.get(req, "thumbnail", "48", "i/p")
     self.assertEqual(resp.status_code, 404)
Example #21
0
    def test_exec_add_call_slashes2dash(self):
        """
        Test workspace add execution call slashes2dash function
        for name argument.
        """
        args = Mock()
        args.workspace_subcommand = "add"
        args.name = "foo"
        args.path = "/foo"
        self.subcommand.ws = Mock()

        with patch("yoda.subcommand.workspace.slashes2dash") as s2d:
            self.subcommand.execute(args)

        s2d.assert_called_once_with("foo")
Example #22
0
    def test_bulk_add_pkg(self, getreg):
        from cheeseprism.index import bulk_add_pkgs

        self.im = self.make_one()
        pkg = stuf(name="dummypackage", version="0.1", filename=self.dummy.name)
        pkgs = (pkg,)
        index = Mock(name="index")
        index.path = self.im.path
        leaves, archs = bulk_add_pkgs(index, pkgs)

        assert len(archs) == 1
        assert len(leaves) == 1
        assert "dummypackage" in leaves
        assert archs[0].basename() == u"dummypackage-0.0dev.tar.gz"
        assert index.regenerate_leaf.called
Example #23
0
 def test_img_404_cold_cache(self):
     """
     Basic 404: requested image is not found. Make sure proper response
     headers are set and the 404 was cached.
     """
     req = Mock()
     req.path = "/lt_cache/thumbnail/48/i/p.jpg"
     with patch("lazythumbs.views.cache", MockCache()) as mc:
         resp = self.renderer.get(req, "thumbnail", "48", "i/p")
     self.assertEqual(resp.status_code, 404)
     self.assertEqual(resp["Content-Type"], "image/jpeg")
     self.assertTrue("Cache-Control" in resp)
     self.assertEqual(len(mc.cache.keys()), 1)
     key = mc.cache.keys()[0]
     cached = mc.cache[key]
     self.assertEqual(cached, 1)
Example #24
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_should_return_list_with_empty_string_and_action_string_when_configuration_directory_has_been_created_in_commit(
        self
    ):

        mock_svn_service = Mock(SvnService)
        mock_svn_service.config_url = "svn://url/for/configuration/repository"
        mock_svn_service.path_to_config = "/config"
        mock_info = Mock()
        mock_path_object = Mock()
        mock_path_object.path = "/config/"
        mock_path_object.action = "A"
        mock_info.changed_paths = [mock_path_object]
        mock_svn_service.get_logs_for_revision.return_value = [mock_info]

        actual = SvnService.get_changed_paths_with_action(mock_svn_service, "1980")

        self.assertEqual([("", "A")], actual)
Example #26
0
    def test_notify_packages_added(self, getreg):
        from cheeseprism.index import notify_packages_added

        pkg = stuf(name="dummypackage", version="0.1", filename=self.dummy.name)
        pkgs = (pkg,)
        index = Mock(name="index")
        index.path = self.im.path
        reg = getreg.return_value = Mock(name="registry")
        out = list(notify_packages_added(index, pkgs))

        assert len(out) == 1
        assert getreg.called
        assert reg.notify.called
        (event,), _ = reg.notify.call_args
        assert event.im is index
        assert event.version == "0.1"
        assert event.name == "dummypackage"
Example #27
0
    def test_configure_extension_saving(self):
        """Testing configure_extension with saving settings"""

        class TestSettingsForm(SettingsForm):
            mykey = forms.CharField(max_length=100)

        self.extension.is_configurable = True
        self.spy_on(self.manager.get_enabled_extension, call_fake=lambda *args: self.extension)

        request = Mock()
        request.path = "/config"
        request.method = "POST"
        request.META = {"CSRF_COOKIE": "abc123"}
        request.POST = {"mykey": "myvalue"}
        request.FILES = {}

        configure_extension(request, TestExtensionWithRegistration, TestSettingsForm, self.manager)

        self.assertEqual(self.extension.settings.get("mykey"), "myvalue")
Example #28
0
    def test_fileAdded(self):
        from niprov.commandline import Commandline

        self.dependencies.config.verbosity = "info"
        cmd = Commandline(self.dependencies)
        cmd.log = Mock()
        img = Mock()
        img.path = "xyz"
        img.status = "new"
        cmd.fileAdded(img)
        cmd.log.assert_called_with("info", "New file: xyz")
        img.status = "series-new-file"
        img.provenance = {"filesInSeries": [1, 2, 3]}
        img.getSeriesId.return_value = "series987"
        cmd.fileAdded(img)
        cmd.log.assert_called_with("info", "Added 3rd file to series: series987")
        img.status = "new-version"
        cmd.fileAdded(img)
        cmd.log.assert_called_with("info", "Added new version for: xyz")
Example #29
0
    def test_create_token_handler(self):
        path = "/token"

        request_mock = Mock(spec=Request)
        request_mock.path = path
        request_mock.post_param.return_value = "authorization_code"

        server_mock = Mock()
        server_mock.authorize_path = "/auth"
        server_mock.token_path = path
        server_mock.access_token_store = Mock(spec=AccessTokenStore)
        server_mock.auth_code_store = Mock()
        server_mock.client_store = Mock()
        server_mock.token_generator = Mock()

        factory = AuthorizationCodeGrant()
        result_class = factory(request_mock, server_mock)

        request_mock.post_param.assert_called_with("grant_type")
        self.assertTrue(isinstance(result_class, AuthorizationCodeTokenHandler))
 def test_is_ros_in_setupfile(self):
     try:
         mock_subprocess = Mock()
         mock_process = Mock(name="mockprocess")
         mock_subprocess.Popen.return_value = mock_process
         mock_process.communicate.return_value = ("/somewhere/mock_ros_root/foo/..", None)
         mock_os = Mock()
         mock_path = Mock()
         mock_os.path = mock_path
         mock_os.environ = {}
         mock_path.split = os.path.split
         mock_path.normpath = os.path.normpath
         mock_path.isfile.return_value = True
         rosinstall.helpers.subprocess = mock_subprocess
         rosinstall.helpers.os = mock_os
         result = rosinstall.helpers.get_ros_root_from_setupfile("fooroot/foodir/setup.sh")
         self.assertEqual("/somewhere/mock_ros_root", os.path.normpath(result))
     finally:
         rosinstall.helpers.subprocess = subprocess
         rosinstall.helpers.os = os