Example #1
0
    def test_if_we_commit_after_a_key_append(self):
        key_path = "tests/fixtures/simple_key.pub"

        mock_file = MagicMock()
        mock_file.__str__ = lambda x: key_path
        mock_path = MagicMock(return_value=mock_file)

        mock_hashlib = MagicMock()
        mock_hashlib.md5.hexdigest.return_value = "HASH"

        mock_user = MagicMock()
        mock_user.path = "path"
        mock_user.name = "test"

        with patch.multiple('models.lists.keys',
                            Path=mock_path,
                            hashlib=mock_hashlib):
            keys = ListKeys(mock_user)

            keys.append(key_path)

        mock_path.has_calls([
            call("path", key_path),
            call("path", "keydir", "HASH"),
            call(mock_file, "test"),
        ])

        eq_(mock_file.isfile.call_count, 1)
        eq_(mock_file.mkdir.call_count, 1)
        mock_file.write_file.assert_called_once_with('nothing to see here\n')
Example #2
0
  def test_list_remove(self):
    key = "my_awesome_key"

    mock_file = MagicMock()
    mock_file.__str__ = lambda x: key
    mock_file.exists.return_value = True
    mock_path = MagicMock(return_value=mock_file)

    mock_hashlib = MagicMock()
    mock_hashlib.md5.hexdigest.return_value = "HASH"

    mock_user = MagicMock()
    mock_user.path = "path"
    mock_user.name = "test"

    with patch.multiple('models.lists.keys', Path=mock_path,
                        hashlib=mock_hashlib):
      keys = ListKeys(mock_user)

      keys.remove(key)

      mock_path.has_calls([
          call("path", 'keydir', 'HASH'),
          call(mock_file, "test.pub"),
      ])

      commit_message = "Removed key for user test"
      mock_user.git.commit.has_calls([call(["my_awesome_key"],
                                           commit_message,
                                           action='remove')])
Example #3
0
 def test015_new_file_existing(self, m_sha256sum):
     m_file = MagicMock()
     m_file.path = "whatever"
     self.File.load_from_sha256.return_value = m_file
     fobj, session = MagicMock(), MagicMock()
     res = module._new_file(fobj, session)
     self.assertEqual(res, m_file)
Example #4
0
    def get_request(
        self, package=None, perms="", user=None, use_base_url=False, path=None
    ):
        """ Construct a fake request """
        request = MagicMock()
        request.registry.fallback = self.fallback
        request.registry.always_show_upstream = self.always_show_upstream
        request.registry.fallback_url = self.fallback_url
        request.registry.fallback_base_url = (
            self.fallback_base_url if use_base_url else None
        )
        request.userid = user
        request.access.can_update_cache = lambda: "c" in perms
        request.access.has_permission.side_effect = lambda n, p: "r" in perms
        request.is_logged_in = user is not None
        request.request_login = six.create_bound_method(_request_login, request)
        pkgs = []
        if package is not None:
            pkgs.append(package)

        if path is not None:
            request.path = path

        request.db.all.return_value = pkgs
        return request
Example #5
0
    def test_generate_deploy_script_withRestartOption_ShouldPrintStopStart(self):
        expected_script = """\
# Rollback information saved in {0}rollback-info_test
:stop-servers()

undeploy abc-v1.0.0 --keep-content --all-relevant-server-groups

deploy {1} --runtime-name=abc.war --name=abc-v1.2.3 --server-groups=group
:start-servers()\
""".format(current_dir + os.sep,
           current_dir + os.sep + "v1.2.3" + os.sep + "abc.war")

        args = MagicMock()
        args.path = current_dir + os.sep + "v1.2.3"
        args.undeploy_pattern = None
        args.undeploy_tag = None
        args.restart = True

        mock_controller = MagicMock()
        mock_controller.domain = True
        deploy.common.initialize_controller = MagicMock(
            return_value=mock_controller
        )

        script = deploy.generate_deploy_script(args)

        self.assertEqual(script, expected_script)
Example #6
0
    def test_users_set(self):
        mocked_repo = MagicMock()
        mocked_repository = MagicMock(config="")
        mocked_repository.get_config.return_value = ""
        mocked_user = MagicMock()

        mock_single_user = MagicMock()
        mock_single_user.name = 'user'

        mocked_repository.name = 'test_repo'
        mocked_repository.path = 'path'

        mocked_user.get.return_value = mock_single_user

        with patch.multiple('pyolite.models.lists.users',
                            Repo=MagicMock(return_value=mocked_repo),
                            User=mocked_user):
            repo_users = ListUsers(mocked_repository)
            repo_users.set((('mocked', 'R'), ('mocked', 'RW+')))

            serialized_users = "repo test_repo\n    R     =    user\n" \
                               "    RW+     =    user\n"
            mocked_repo.overwrite.assert_called_once_with(serialized_users)

            message = "Initialized repository test_repo with users: test, user"
            mocked_repository.git.commit.has_calls([call(['conf'], message)])
Example #7
0
    def test_users_set(self):
        mocked_repo = MagicMock()
        mocked_repository = MagicMock()
        mocked_user = MagicMock()

        mock_single_user = MagicMock()
        mock_single_user.name = 'user'

        mocked_repository.name = 'test_repo'
        mocked_repository.path = 'path'

        mocked_user.get.return_value = mock_single_user

        with patch.multiple('pyolite.models.lists.users',
                            Repo=MagicMock(return_value=mocked_repo),
                            User=mocked_user):
            repo_users = ListUsers(mocked_repository)
            repo_users.set((('mocked', 'R'), ('mocked', 'RW+')))

            serialized_users = "repo test_repo\n    R     =    user\n" \
                               "    RW+     =    user\n"
            mocked_repo.overwrite.assert_called_once_with(serialized_users)

            message = "Initialized repository test_repo with users: test, user"
            mocked_repository.git.commit.has_calls([call(['conf'], message)])
Example #8
0
    def test_user_edit_invalid_permissions(self):
        mocked_repo = MagicMock()
        mocked_repository = MagicMock()
        mocked_user = MagicMock()

        mock_single_user = MagicMock()
        mock_single_user.name = 'another_user'
        mock_single_user.__str__ = lambda x: 'another_user'

        mocked_repository.name = 'test_repo'
        mocked_repository.path = 'path'

        mocked_user.get.return_value = mock_single_user
        mocked_repo.users = ['another_user']

        with patch.multiple('pyolite.models.lists.users',
                            Repo=MagicMock(return_value=mocked_repo),
                            User=mocked_user):
            repo_users = ListUsers(mocked_repository)
            repo_users.edit('test', 'X')

            pattern = r'(\s*)([RW+DC]*)(\s*)=(\s*)%s' % 'another_user'
            string = r"\n    %s    =    %s" % ('X', 'another_user')
            mocked_repo.replace.assert_called_once_with(pattern, string)

            message = "User another_user edit invalid permission for repository test_repo"
            mocked_repository.git.commit.has_calls([call(['conf'], message)])
Example #9
0
    def test_it_should_add_a_new_user_to_repo_if_is_valid(self):
        mocked_repo = MagicMock()
        mocked_repository = MagicMock()
        mocked_user = MagicMock()

        mock_single_user = MagicMock()
        mock_single_user.name = 'another_user'
        mock_single_user.__str__ = lambda x: 'another_user'

        mocked_repository.name = 'test_repo'
        mocked_repository.path = 'path'

        mocked_user.get.return_value = mock_single_user
        mocked_repo.users = ['user']

        with patch.multiple('pyolite.models.lists.users',
                            Repo=MagicMock(return_value=mocked_repo),
                            User=mocked_user):
            repo_users = ListUsers(mocked_repository)
            repo_users.add('test', 'RW+')

            content = '    RW+     =    another_user\n'
            mocked_repo.write.assert_called_once_with(content)

            message = 'User another_user added to repo test_repo ' \
                      'with permissions: RW+'
            mocked_repository.git.commit.has_calls([call(['conf'], message)])
Example #10
0
 def test034_launch_asynchronous_ftp_error(self,
                                           m_session_transaction,
                                           m_Scan,
                                           m_ftp_ctrl,
                                           m_add_empty_result):
     m_scan, m_session = MagicMock(), MagicMock()
     fw1, fw2 = MagicMock(), MagicMock()
     file1, file2 = MagicMock(), MagicMock()
     pathf1, pathf2 = 'path-file1', 'path-file2'
     file1.path = pathf1
     file2.path = pathf2
     fw1.file.sha256 = "sha256file1"
     fw1.file.mimetype = "mimetypefile1"
     fw2.file.sha256 = "sha256file2"
     fw2.file.mimetype = "mimetypefile2"
     m_scan.files_web = [fw1, fw2]
     m_scan.files = [file1, file2]
     probe1, probe2 = "Probe1", "Probe2"
     probelist = [probe1, probe2]
     m_scan.get_probe_list.return_value = probelist
     m_add_empty_result.return_value = probelist
     m_session_transaction().__enter__.return_value = m_session
     m_scan.status = IrmaScanStatus.ready
     m_scan.mimetype_filtering = False
     m_Scan.load_from_ext_id.return_value = m_scan
     scanid = "scanid"
     m_ftp_ctrl.upload_scan.side_effect = IrmaFtpError()
     module.launch_asynchronous(scanid)
     expected = IrmaScanStatus.error_ftp_upload
     m_scan.set_status.assert_called_once_with(expected)
Example #11
0
 def test015_new_file_existing(self, m_sha256sum):
     m_file = MagicMock()
     m_file.path = "whatever"
     self.File.load_from_sha256.return_value = m_file
     fobj, session = MagicMock(), MagicMock()
     res = module._new_file(fobj, session)
     self.assertEqual(res, m_file)
Example #12
0
    def get_request(
        self, package=None, perms="", user=None, use_base_url=False, path=None
    ):
        """Construct a fake request"""
        request = MagicMock()
        request.registry.fallback = self.fallback
        request.registry.always_show_upstream = self.always_show_upstream
        request.registry.fallback_url = self.fallback_url
        request.registry.fallback_base_url = (
            self.fallback_base_url if use_base_url else None
        )
        request.userid = user
        request.access.can_update_cache = lambda: "c" in perms
        request.access.has_permission.side_effect = lambda n, p: "r" in perms
        request.is_logged_in = user is not None
        request.request_login = MethodType(_request_login, request)
        pkgs = []
        if package is not None:
            pkgs.append(package)

        if path is not None:
            request.path = path

        request.db.all.return_value = pkgs
        return request
Example #13
0
    def test_user_removing(self):
        mocked_repo = MagicMock()
        mocked_repository = MagicMock()
        mocked_user = MagicMock()

        mock_single_user = MagicMock()
        mock_single_user.name = 'another_user'
        mock_single_user.__str__ = lambda x: 'another_user'

        mocked_repository.name = 'test_repo'
        mocked_repository.path = 'path'

        mocked_user.get.return_value = mock_single_user
        mocked_repo.users = ['user']

        with patch.multiple('pyolite.models.lists.users',
                            Repo=MagicMock(return_value=mocked_repo),
                            User=mocked_user):
            repo_users = ListUsers(mocked_repository)
            repo_users.remove('test')

            pattern = r'(\s*)([RW+DC]*)(\s*)=(\s*)%s' % 'another_user'
            mocked_repo.replace.assert_called_once_with(pattern, "")

            message = "Deleted user another_user from repository test_repo"
            mocked_repository.git.commit.has_calls([call(['conf'], message)])
 def TestCommandParsing(self):
     request = MagicMock()
     request.path = "/test"
     request.query = "item1=value1"
     request.remote_ip = "1.2.3.4"
     request.method = "PUT"
     request.headers = {
         'User': '******',
         'Creation-Time': 'test_time',
         'User-Agent': 'test_user_agent'
     }
     request.body="item2=value2&item2=value3&item2=value4"
     self.command = Command(request)
     self.assertEqual(self.command.command_name, 'test')
     self.assertEqual(self.command.command_type, 'PUT')
     self.assertEqual(self.command.has_param('item1'), True)
     self.assertEqual(self.command.has_param('item2'), True)
     self.assertEqual(self.command.has_param('item3'), False)
     self.assertEqual(self.command.get_param('item1'), 'value1')
     self.assertEqual('value2' in self.command.get_param('item2'), True)
     self.assertEqual('value3' in self.command.get_param('item2'), True)
     self.assertEqual('value4' in self.command.get_param('item2'), True)
     data = self.command.format_trace
     self.assertEqual(data['Username'], 'test_user')
     self.assertEqual(data['Created'], 'test_time')
     self.assertEqual(data['Source_Address'], '1.2.3.4')
     self.assertEqual(data['Source_ID'], 'test_user_agent')
Example #15
0
  def test_user_edit_permissions(self):
    mocked_repo = MagicMock()
    mocked_repository = MagicMock()
    mocked_user = MagicMock()

    mock_single_user = MagicMock()
    mock_single_user.name = 'another_user'
    mock_single_user.__str__ = lambda x: 'another_user'

    mocked_repository.name = 'test_repo'
    mocked_repository.path = 'path'

    mocked_user.get.return_value = mock_single_user
    mocked_repo.users = ['user']

    with patch.multiple('models.lists.users',
                        Repo=MagicMock(return_value=mocked_repo),
                        User=mocked_user):
      repo_users = ListUsers(mocked_repository)
      repo_users.edit('test', 'R')

      pattern = r'(\s*)([RW+DC]*)(\s*)=(\s*)%s' % 'another_user'
      string = r"\n    %s    =    %s" % ('R', 'another_user')
      mocked_repo.replace.assert_called_once_with(pattern, string)

      message = "User another_user has R permission for repository test_repo"
      mocked_repository.git.commit.has_calls([call(['conf'], message)])
Example #16
0
 def test_new_file_existing_deleted(self, m_sha256sum, m_build_sha256_path,
                                    m_save_to_file, m_os):
     m_file = MagicMock()
     fobj = MagicMock()
     m_file.path = "filepath"
     sha256val = "whatever"
     m_os.path.exists(m_file.path).return_value = False
     m_sha256sum.return_value = sha256val
     m_session = MagicMock()
     m_session.query(module.File).filter(
         module.File.sha256 == sha256val).one.return_value = m_file
     m_file.path = None
     res = module.File.get_or_create(fobj, m_session)
     m_build_sha256_path.assert_called()
     m_save_to_file.assert_called()
     self.assertEqual(res, m_file)
Example #17
0
  def test_it_should_add_a_new_user_to_repo_if_is_valid(self):
    mocked_repo = MagicMock()
    mocked_repository = MagicMock()
    mocked_user = MagicMock()

    mock_single_user = MagicMock()
    mock_single_user.name = 'another_user'
    mock_single_user.__str__ = lambda x: 'another_user'

    mocked_repository.name = 'test_repo'
    mocked_repository.path = 'path'

    mocked_user.get.return_value = mock_single_user
    mocked_repo.users = ['user']

    with patch.multiple('models.lists.users',
                        Repo=MagicMock(return_value=mocked_repo),
                        User=mocked_user):
      repo_users = ListUsers(mocked_repository)
      repo_users.add('test', 'RW+')

      content = '    RW+     =    another_user\n'
      mocked_repo.write.assert_called_once_with(content)

      message = 'User another_user added to repo test_repo ' \
                'with permissions: RW+'
      mocked_repository.git.commit.has_calls([call(['conf'], message)])
Example #18
0
  def test_user_removing(self):
    mocked_repo = MagicMock()
    mocked_repository = MagicMock()
    mocked_user = MagicMock()

    mock_single_user = MagicMock()
    mock_single_user.name = 'another_user'
    mock_single_user.__str__ = lambda x: 'another_user'

    mocked_repository.name = 'test_repo'
    mocked_repository.path = 'path'

    mocked_user.get.return_value = mock_single_user
    mocked_repo.users = ['user']

    with patch.multiple('models.lists.users',
                        Repo=MagicMock(return_value=mocked_repo),
                        User=mocked_user):
      repo_users = ListUsers(mocked_repository)
      repo_users.remove('test')

      pattern = r'(\s*)([RW+DC]*)(\s*)=(\s*)%s' % 'another_user'
      mocked_repo.replace.assert_called_once_with(pattern, "")

      message = "Deleted user another_user from repository test_repo"
      mocked_repository.git.commit.has_calls([call(['conf'], message)])
Example #19
0
 def test034_launch_asynchronous_ftp_error(self,
                                           m_session_transaction,
                                           m_Scan,
                                           m_ftp_ctrl,
                                           m_add_empty_result):
     m_scan, m_session = MagicMock(), MagicMock()
     fw1, fw2 = MagicMock(), MagicMock()
     file1, file2 = MagicMock(), MagicMock()
     pathf1, pathf2 = 'path-file1', 'path-file2'
     file1.path = pathf1
     file2.path = pathf2
     fw1.file.sha256 = "sha256file1"
     fw1.file.mimetype = "mimetypefile1"
     fw2.file.sha256 = "sha256file2"
     fw2.file.mimetype = "mimetypefile2"
     m_scan.files_web = [fw1, fw2]
     m_scan.files = [file1, file2]
     probe1, probe2 = "Probe1", "Probe2"
     probelist = [probe1, probe2]
     m_scan.get_probe_list.return_value = probelist
     m_add_empty_result.return_value = probelist
     m_session_transaction().__enter__.return_value = m_session
     m_scan.status = IrmaScanStatus.ready
     m_scan.mimetype_filtering = False
     m_Scan.load_from_ext_id.return_value = m_scan
     scanid = "scanid"
     m_ftp_ctrl.upload_scan.side_effect = IrmaFtpError()
     module.launch_asynchronous(scanid)
     expected = IrmaScanStatus.error_ftp_upload
     m_scan.set_status.assert_called_once_with(expected)
Example #20
0
  def test_if_we_commit_after_a_key_append(self):
    key_path = "tests/fixtures/simple_key.pub"

    mock_file = MagicMock()
    mock_file.__str__ = lambda x: key_path
    mock_path = MagicMock(return_value=mock_file)

    mock_hashlib = MagicMock()
    mock_hashlib.md5.hexdigest.return_value = "HASH"

    mock_user = MagicMock()
    mock_user.path = "path"
    mock_user.name = "test"

    with patch.multiple('models.lists.keys', Path=mock_path,
                        hashlib=mock_hashlib):
      keys = ListKeys(mock_user)

      keys.append(key_path)

    mock_path.has_calls([
        call("path", key_path),
        call("path", "keydir", "HASH"),
        call(mock_file, "test"),
    ])

    eq_(mock_file.isfile.call_count, 1)
    eq_(mock_file.mkdir.call_count, 1)
    mock_file.write_file.assert_called_once_with('nothing to see here\n')
Example #21
0
    def test_list_remove(self):
        key = "my_awesome_key"

        mock_file = MagicMock()
        mock_file.__str__ = lambda x: key
        mock_file.exists.return_value = True
        mock_path = MagicMock(return_value=mock_file)

        mock_hashlib = MagicMock()
        mock_hashlib.md5.hexdigest.return_value = "HASH"

        mock_user = MagicMock()
        mock_user.path = "path"
        mock_user.name = "test"

        with patch.multiple('models.lists.keys',
                            Path=mock_path,
                            hashlib=mock_hashlib):
            keys = ListKeys(mock_user)

            keys.remove(key)

            mock_path.has_calls([
                call("path", 'keydir', 'HASH'),
                call(mock_file, "test.pub"),
            ])

            commit_message = "Removed key for user test"
            mock_user.git.commit.has_calls(
                [call(["my_awesome_key"], commit_message, action='remove')])
Example #22
0
 def test_download_deleted_file(self, m_File, m_open):
     sha256 = "whatever"
     m_fobj = MagicMock()
     m_fobj.path = None
     m_File.load_from_sha256.return_value = m_fobj
     with self.assertRaises(IrmaDatabaseResultNotFound) as context:
         api_files._download(sha256, self.db)
     self.assertEqual(str(context.exception), "downloading a removed file")
Example #23
0
 def test_wizard(self):
     args = Mock()
     args.path = '/tmp/foo'
     cli.getch = Mock(side_effect=chain(repeat('b', 10), 'c',
                                        repeat('b', 10)))
     cli.get_devices = Mock(side_effect=self.devices)
     spreads.config['keep'] = False
     cli.wizard(args, self.devices)
Example #24
0
 def test_search(self, search):
     search.return_value = (("foo", "foodesc"),)
     repo = MagicMock()
     repo.path = "/dev/null"
     self.assertEqual(
         list(bw_repo_plugin_search(repo, MagicMock())),
         ["foo: foodesc"],
     )
Example #25
0
 def test_list(self, listmethod):
     listmethod.return_value = (("foo", 1),)
     repo = MagicMock()
     repo.path = "/dev/null"
     self.assertEqual(
         list(bw_repo_plugin_list(repo, MagicMock())),
         ["foo (v1)"],
     )
Example #26
0
 def test_new_file_existing_deleted(self, m_sha256sum, m_build_sha256_path,
                                    m_save_to_file, m_os):
     m_file = MagicMock()
     fobj = MagicMock()
     m_file.path = "filepath"
     sha256val = "whatever"
     m_os.path.exists(m_file.path).return_value = False
     m_sha256sum.return_value = sha256val
     m_session = MagicMock()
     m_session.query(module.File).filter(
             module.File.sha256 == sha256val
     ).one.return_value = m_file
     m_file.path = None
     res = module.File.get_or_create(fobj, m_session)
     m_build_sha256_path.assert_called()
     m_save_to_file.assert_called()
     self.assertEqual(res, m_file)
Example #27
0
 def test_download(self):
     args = Mock()
     args.path = '/tmp/foo'
     spreads.config['keep'] = False
     cli.get_devices = Mock(return_value=self.devices)
     cli.download(args=args)
     assert cli.workflow.download.call_args == call(self.devices,
                                                    '/tmp/foo')
Example #28
0
 def test_wizard(self):
     args = Mock()
     args.path = '/tmp/foo'
     cli.getch = Mock(
         side_effect=chain(repeat('b', 10), 'c', repeat('b', 10)))
     cli.get_devices = Mock(side_effect=self.devices)
     spreads.config['keep'] = False
     cli.wizard(args, self.devices)
Example #29
0
 def test_download(self):
     args = Mock()
     args.path = '/tmp/foo'
     spreads.config['keep'] = False
     cli.get_devices = Mock(return_value=self.devices)
     cli.download(args=args)
     assert cli.workflow.download.call_args == call(self.devices,
                                                    '/tmp/foo')
Example #30
0
 def test016_download_deleted_file(self, m_File, m_open):
     sha256 = "whatever"
     m_fobj = MagicMock()
     m_fobj.path = None
     m_File.load_from_sha256.return_value = m_fobj
     with self.assertRaises(IrmaDatabaseResultNotFound) as context:
         api_files._download(sha256, self.db)
     self.assertEqual(str(context.exception), "downloading a removed file")
Example #31
0
def test_missing_asset():
    with pytest.raises(KeyError):
        fs = mock_fs().withPage('pages/foo/bar')
        with mock_fs_scope(fs):
            page = MagicMock()
            page.app = fs.getApp(cache=False)
            page.path = fs.path('/kitchen/pages/foo/bar.md')
            assetor = Assetor(page, '/foo/bar')
            assetor['this_doesnt_exist']
Example #32
0
 def test016_new_file_existing_deleted(self, m_save_to_file, m_sha256sum):
     m_file = MagicMock()
     self.File.load_from_sha256.return_value = m_file
     fobj, session = MagicMock(), MagicMock()
     path = "testpath"
     self.build_sha256_path.return_value = path
     m_file.path = None
     module._new_file(fobj, session)
     m_save_to_file.assert_called_once_with(fobj, path)
Example #33
0
 def test_custom_brain_fails(self):
     self.m_simconf.brain_model.is_custom = True
     model = MagicMock()
     model.name = 'model_brain'
     model.path = 'brains'
     model.type = 'brains/brain.zip'
     self.launcher._storageClient.get_model.return_value = None
     self.assertRaises(NRPServicesGeneralException,
                       self.launcher._load_brain)
Example #34
0
def test_missing_asset():
    with pytest.raises(KeyError):
        fs = mock_fs().withPage('pages/foo/bar')
        with mock_fs_scope(fs):
            page = MagicMock()
            page.app = fs.getApp(cache=False)
            page.path = fs.path('/kitchen/pages/foo/bar.md')
            assetor = Assetor(page, '/foo/bar')
            assetor['this_doesnt_exist']
Example #35
0
    def test_cli_uget_create_with_config_json(self, unitypackage_runner_mock,
                                              csproj_mock):
        """Test cli: uget create with options loaded via config json"""

        invocation_results = [False]

        # Mock running Unity to export unity package
        def export_unitypackage_mock(*args, **kwargs):
            assert 'CustomUnityProject' in args[0]  # In temp folder
            assert args[0] == os.path.normpath(
                'CustomUnityProject/Assets/MyUnityPackage')
            assert args[1] == os.path.normpath(
                'CustomOutput/TestProject_1.0.0_Debug.unitypackage')
            create_empty_file(args[1])
            invocation_results[0] = True
            return 0

        unitypackage_runner_instance = MagicMock()
        unitypackage_runner_instance.export_unitypackage = export_unitypackage_mock
        unitypackage_runner_mock.return_value = unitypackage_runner_instance

        csproj_instance = MagicMock()
        csproj_instance.get_assembly_name.return_value = "TestProject"
        csproj_instance.get_assembly_version.return_value = "1.0.0"
        csproj_instance.get_output_path.return_value = "bin/Output/Debug"
        csproj_instance.path = "TestProject.csproj"
        csproj_mock.return_value = csproj_instance

        config_data = {
            "output_dir": "CustomOutput",
            "configuration": "Debug",
            "unity_project_path": "CustomUnityProject",
            "root_dir": "MyUnityPackage",
            "clean": True,
        }

        runner = CliRunner(env={})
        with runner.isolated_filesystem():
            os.makedirs("bin/Output/Debug")
            create_empty_file("bin/Output/Debug/TestProject.dll")
            create_empty_file("bin/Output/Debug/TestProject.pdb")
            os.makedirs("CustomOutput/")
            create_empty_file(
                "CustomOutput/TestProject_0.1.0_Release.unitypackage"
            )  # Should be removed

            result = runner.invoke(
                cli.ugetcli, ['create', '--config',
                              json.dumps(config_data)],
                obj={})

            assert not os.path.isfile(
                "Output/TestProject_0.1.0_Release.unitypackage")

        assert result.exit_code == 0, result
        unitypackage_runner_mock.assert_called_with(False)
        assert invocation_results[0], "did not invoke export_unitypackage_mock"
Example #36
0
 def test016_new_file_existing_deleted(self, m_save_to_file, m_sha256sum):
     m_file = MagicMock()
     self.File.load_from_sha256.return_value = m_file
     fobj, session = MagicMock(), MagicMock()
     path = "testpath"
     self.build_sha256_path.return_value = path
     m_file.path = None
     module._new_file(fobj, session)
     m_save_to_file.assert_called_once_with(fobj, path)
Example #37
0
    def test_paginate_returns_this_paginator(self):
        request = MagicMock()
        request.GET.get.return_value = 1
        request.GET.urlencode.return_value = ''
        request.path = ''

        qs = Addon.search()
        pager = paginate(request, qs)
        assert isinstance(pager.paginator, ESPaginator)
Example #38
0
    def test_paginate_returns_this_paginator(self):
        request = MagicMock()
        request.GET.get.return_value = 1
        request.GET.urlencode.return_value = ''
        request.path = ''

        qs = Addon.search()
        pager = paginate(request, qs)
        assert isinstance(pager.paginator, ESPaginator)
Example #39
0
 def test_upstream_admin(self):
     req = MagicMock()
     req.headers = {}
     req.method = 'GET'
     req.path = '/v2/servers'
     req.env = {'is_admin': True}
     resp = MagicMock()
     validate_token(req, resp, {})
     self.assertIsNone(req.env.get('auth'))
Example #40
0
 def test_upstream_admin(self):
     req = MagicMock()
     req.headers = {}
     req.method = 'GET'
     req.path = '/v2/servers'
     req.env = {'is_admin': True}
     resp = MagicMock()
     validate_token(req, resp, {})
     self.assertIsNone(req.env.get('auth'))
Example #41
0
 def test_upstream_xauth(self):
     req = MagicMock()
     req.headers = {}
     req.method = 'GET'
     req.path = '/v2/servers'
     req.env = {'REMOTE_USER': '******'}
     resp = MagicMock()
     validate_token(req, resp, {})
     self.assertIsNone(req.env.get('auth'))
Example #42
0
    def test_subreddit_subscribe_event_from_onboarding(self):
        context = MagicMock(name="context")
        context.user._age.total_seconds.return_value = 1000
        request = MagicMock(name="request")
        request.ip = "1.2.3.4"

        subreddit = MagicMock(name="subreddit")
        subreddit._age.total_seconds.return_value = 1000
        subreddit._id = 1
        subreddit.name = 'cats'
        subreddit.path = '/r/cats/'

        g.events.subreddit_subscribe_event(
            True,
            False,
            subreddit,
            context.user,
            1,
            is_onboarding=True,
            request=request,
            context=context,
        )

        g.events.queue_production.assert_event_item(
            {
                'event_type': "ss.subscribe",
                'event_topic': "subscribe_events",
                "payload": {
                    'base_url': subreddit.path,
                    'is_first_subscription': False,
                    'sr_age': 1000000,
                    'sr_id': subreddit._id,
                    'sr_name': subreddit.name,
                    'user_age': 1000000,
                    'user_subscription_size': 1,
                    'domain': request.host,
                    'referrer_domain': self.domain_mock(),
                    'user_id': context.user._id,
                    'user_name': context.user.name,
                    'user_features': context.user.user_features,
                    'referrer_url': request.headers.get(),
                    'session_referrer_domain': self.domain_mock(),
                    'user_agent': request.user_agent,
                    'user_agent_parsed': request.parsed_agent.to_dict(),
                    'oauth2_client_id': context.oauth2_client._id,
                    'oauth2_client_app_type': context.oauth2_client.app_type,
                    'oauth2_client_name': context.oauth2_client.name,
                    'process_notes': 'onboarding_experiment',
                    'geoip_country': context.location,
                    'obfuscated_data': {
                        'client_ip': request.ip,
                        'client_ipv4_24': "1.2.3",
                        'client_ipv4_16': "1.2",
                    },
                },
            }
        )
Example #43
0
 def test_upstream_xauth(self):
     req = MagicMock()
     req.headers = {}
     req.method = 'GET'
     req.path = '/v2/servers'
     req.env = {'REMOTE_USER': '******'}
     resp = MagicMock()
     validate_token(req, resp, {})
     self.assertIsNone(req.env.get('auth'))
Example #44
0
    def test_search(self):
        middleware = MagicMock()
        middleware.path = ['test']
        middleware.conn.fulltext_search.return_value = {'docs': 'expected'}

        rs2 = RiakSearch2(middleware)
        result = rs2.search('query')

        self.assertEqual(result, 'expected')
        middleware.conn.fulltext_search.assert_called_with('test', 'query')
Example #45
0
 def test_invalid_auth(self):
     req = MagicMock()
     req.headers = {'X-AUTH-TOKEN': 'IAMBAD'}
     req.method = 'GET'
     req.path = '/v2/servers'
     req.env = {}
     resp = MagicMock()
     with self.assertRaises(InvalidTokenError):
         validate_token(req, resp, {})
     self.assertIsNone(req.env.get('auth'))
Example #46
0
 def test_upstream_preauth(self):
     req = MagicMock()
     auth = {'user': '******'}
     req.headers = {}
     req.method = 'GET'
     req.path = '/v2/servers'
     req.env = {'auth': auth}
     resp = MagicMock()
     validate_token(req, resp, {})
     self.assertEquals(req.env.get('auth'), auth)
Example #47
0
 def test_upstream_preauth(self):
     req = MagicMock()
     auth = {'user': '******'}
     req.headers = {}
     req.method = 'GET'
     req.path = '/v2/servers'
     req.env = {'auth': auth}
     resp = MagicMock()
     validate_token(req, resp, {})
     self.assertEquals(req.env.get('auth'), auth)
Example #48
0
 def test_single_update(self, update):
     update.return_value = (1, 2)
     repo = MagicMock()
     repo.path = "/dev/null"
     args = MagicMock()
     args.plugin = "foo"
     self.assertEqual(
         list(bw_repo_plugin_update(repo, args)),
         ["foo: 1 → 2"],
     )
Example #49
0
 def test_invalid_auth(self):
     req = MagicMock()
     req.headers = {'X-AUTH-TOKEN': 'IAMBAD'}
     req.method = 'GET'
     req.path = '/v2/servers'
     req.env = {}
     resp = MagicMock()
     with self.assertRaises(InvalidTokenError):
         validate_token(req, resp, {})
     self.assertIsNone(req.env.get('auth'))
Example #50
0
    def test_subreddit_subscribe_event_from_onboarding(self):
        context = MagicMock(name="context")
        context.user._age.total_seconds.return_value = 1000
        request = MagicMock(name="request")
        request.ip = "1.2.3.4"

        subreddit = MagicMock(name="subreddit")
        subreddit._age.total_seconds.return_value = 1000
        subreddit._id = 1
        subreddit.name = 'cats'
        subreddit.path = '/r/cats/'

        g.events.subreddit_subscribe_event(
            True,
            False,
            subreddit,
            context.user,
            1,
            is_onboarding=True,
            request=request,
            context=context,
        )

        g.events.queue_production.assert_event_item({
            'event_type': "ss.subscribe",
            'event_topic': "subscribe_events",
            "payload": {
                'base_url': subreddit.path,
                'is_first_subscription': False,
                'sr_age': 1000000,
                'sr_id': subreddit._id,
                'sr_name': subreddit.name,
                'user_age': 1000000,
                'user_subscription_size': 1,
                'domain': request.host,
                'referrer_domain': self.domain_mock(),
                'user_id': context.user._id,
                'user_name': context.user.name,
                'user_features': context.user.user_features,
                'referrer_url': request.headers.get(),
                'session_referrer_domain': self.domain_mock(),
                'user_agent': request.user_agent,
                'user_agent_parsed': request.parsed_agent.to_dict(),
                'oauth2_client_id': context.oauth2_client._id,
                'oauth2_client_app_type': context.oauth2_client.app_type,
                'oauth2_client_name': context.oauth2_client.name,
                'process_notes': 'onboarding_experiment',
                'geoip_country': context.location,
                'obfuscated_data': {
                    'client_ip': request.ip,
                    'client_ipv4_24': "1.2.3",
                    'client_ipv4_16': "1.2",
                },
            },
        })
Example #51
0
 def test_all_update(self, update, listmethod):
     update.return_value = (1, 2)
     listmethod.return_value = (("foo", 1),)
     repo = MagicMock()
     repo.path = "/dev/null"
     args = MagicMock()
     args.plugin = None
     self.assertEqual(
         list(bw_repo_plugin_update(repo, args)),
         ["foo: 1 → 2"],
     )
Example #52
0
 def test_unknown_plugin(self, install):
     install.side_effect = NoSuchPlugin
     repo = MagicMock()
     repo.path = "/dev/null"
     args = MagicMock()
     args.force = False
     args.plugin = "foo"
     self.assertEqual(
         list(bw_repo_plugin_install(repo, args)),
         ["unknown plugin 'foo'", 1],
     )
Example #53
0
    def test_log_request(self, log):
        req = MagicMock()
        req.method = 'GET'
        req.path = '/'
        req.query_string = 'something=value'
        req.env = {'REQUEST_ID': '123456'}
        resp = MagicMock()
        resp.status = '200 OK'
        log_request(req, resp)

        log.info.assert_called_with('%s %s %s %s [ReqId: %s]', 'GET', '/',
                                    'something=value', '200 OK', '123456')
Example #54
0
 def test_unprotected(self):
     for api in ['GET:/v2', 'GET:/v2/', 'GET:/v3.0', 'GET:/v3.0/',
                 'GET:/v10.22', 'POST:/v2/tokens', 'POST:/v2.1/tokens',
                 'GET:/v2/tokens/a8Vs7bS', 'GET:/v2.0/tokens/a8Vs7bS']:
         req = MagicMock()
         req.headers = {'X-AUTH-TOKEN': None}
         req.method = api.split(':')[0]
         req.path = api.split(':')[1]
         req.env = {}
         resp = MagicMock()
         validate_token(req, resp, {})
         self.assertIsNone(req.env.get('auth'))
Example #55
0
def test_multiple_assets_with_same_name():
    with pytest.raises(UnsupportedAssetsError):
        fs = (mock_fs().withPage('pages/foo/bar').withPageAsset(
            'pages/foo/bar', 'one.txt',
            'one text').withPageAsset('pages/foo/bar', 'one.jpg',
                                      'one picture'))
        with mock_fs_scope(fs):
            page = MagicMock()
            page.app = fs.getApp(cache=False)
            page.path = fs.path('/kitchen/pages/foo/bar.md')
            assetor = Assetor(page, '/foo/bar')
            assetor['one']
Example #56
0
def test_configuration_load():
    i = 1000
    config = {conf.statement_sleep_seconds.__name__: i}
    fsrw = MagicMock()
    fsrw.path = ""
    read_lines = MagicMock(return_value=[json.dumps(config)])
    fsrw.read_lines = read_lines
    fsrw_class = MagicMock(return_value=fsrw)
    conf.load(fsrw_class)
    assert conf._overrides is not None
    assert_equals(conf._overrides, config)
    assert_equals(conf.statement_sleep_seconds(), i)
Example #57
0
def test_configuration_initialize():
    s = "hello"
    config = {conf.fatal_error_suggestion.__name__: s}
    fsrw = MagicMock()
    fsrw.path = ""
    read_lines = MagicMock(return_value=[json.dumps(config)])
    fsrw.read_lines = read_lines
    fsrw_class = MagicMock(return_value=fsrw)
    conf.initialize(fsrw_class)
    assert conf._overrides is not None
    assert_equals(conf._overrides, config)
    assert_equals(conf.fatal_error_suggestion(), s)
Example #58
0
def test_configuration_load():
    i = 1000
    config = { conf.statement_sleep_seconds.__name__: i }
    fsrw = MagicMock()
    fsrw.path = ""
    read_lines = MagicMock(return_value=[json.dumps(config)])
    fsrw.read_lines = read_lines
    fsrw_class = MagicMock(return_value=fsrw)
    conf.load(fsrw_class)
    assert conf._overrides is not None
    assert_equals(conf._overrides, config)
    assert_equals(conf.statement_sleep_seconds(), i)
Example #59
0
    def test_cli_uget_create_with_clean(self, unitypackage_runner_mock,
                                        csproj_mock):
        """Test cli: uget create with --clean"""

        invocation_results = [False]

        # Mock running Unity to export unity package
        def export_unitypackage_mock(*args, **kwargs):
            assert 'UnityProject' in args[0]  # In temp folder
            assert os.path.normpath(
                'UnityProject/Assets/TestProject') in args[0]
            assert os.path.normpath(
                'Output/TestProject_1.0.0_Release.unitypackage') in args[1]
            create_empty_file(args[1])
            invocation_results[0] = True
            return 0

        unitypackage_runner_instance = MagicMock()
        unitypackage_runner_instance.export_unitypackage = export_unitypackage_mock
        unitypackage_runner_mock.return_value = unitypackage_runner_instance

        csproj_instance = MagicMock()
        csproj_instance.get_assembly_name.return_value = "TestProject"
        csproj_instance.get_assembly_version.return_value = "1.0.0"
        csproj_instance.get_output_path.return_value = "bin/Output/Debug"
        csproj_instance.path = "TestProject.csproj"
        csproj_mock.return_value = csproj_instance

        runner = CliRunner(env={})
        with runner.isolated_filesystem():
            os.makedirs("bin/Output/Debug")
            create_empty_file("bin/Output/Debug/TestProject.dll")
            create_empty_file("bin/Output/Debug/TestProject.pdb")
            os.makedirs("Output/")
            create_empty_file("Output/TestProject_0.1.0_Release.unitypackage"
                              )  # Should be removed
            create_empty_file("Output/TestProject_0.1.1_Release.unitypackage"
                              )  # Should be removed
            create_empty_file("Output/TestProject_0.1.0_Debug.unitypackage"
                              )  # Should NOT be removed
            result = runner.invoke(cli.ugetcli, ['create', '--clean'], obj={})

            assert not os.path.isfile(
                "Output/TestProject_0.1.0_Release.unitypackage")
            assert not os.path.isfile(
                "Output/TestProject_0.1.1_Release.unitypackage")
            assert os.path.isfile(
                "Output/TestProject_0.1.0_Debug.unitypackage")

        assert result.exit_code == 0, result
        unitypackage_runner_mock.assert_called_with(False)
        assert invocation_results[0], "did not invoke export_unitypackage_mock"
Example #60
0
    def test_solve_conflicts_they_deleted_the_file(self):
        mocked_repo = MagicMock()
        mocked_file = MagicMock()

        mocked_file.path = "simple_path"

        def conflicts():
            yield None, None, mocked_file

        mine = AcceptMine(mocked_repo)
        mine.solve_conflicts(conflicts())

        mocked_repo.index.add.assert_called_once_with("simple_path")