Пример #1
0
def get_mock():
    ysc = youtube_status_code
    yu = youtube_url
    yc = youtube_cookies
    yt = youtube_text
    yh = youtube_headers
    yosc = youtube_oembed_status_code
    you = youtube_oembed_url
    yoh = youtube_oembed_headers
    yot = youtube_oembed_text

    mock_obj_1 = Mock()
    mock_obj_1.status_code = ysc
    mock_obj_1.url = yu
    mock_obj_1.headers = yh
    mock_obj_1.cookies = yc
    mock_obj_1.text = yt
    mock_obj_1.json = lambda: json.loads(mock_obj_1.text)

    mock_obj_2 = Mock()
    mock_obj_2.status_code = 200
    mock_obj_2.url = you
    mock_obj_2.headers = yoh
    mock_obj_2.text = yot
    mock_obj_2.json = lambda: json.loads(mock_obj_2.text)

    return [mock_obj_1, mock_obj_1, mock_obj_2]
Пример #2
0
 def create_mock_api(cls):
   """Builds up a mock API object, with a mock SchedulerProxy"""
   mock_scheduler = Mock()
   mock_scheduler.url = "http://something_or_other"
   mock_scheduler_client = Mock()
   mock_scheduler_client.scheduler.return_value = mock_scheduler
   mock_scheduler_client.url = "http://something_or_other"
   mock_api = Mock(spec=HookedAuroraClientAPI)
   mock_api.scheduler_proxy = mock_scheduler_client
   return (mock_api, mock_scheduler_client)
Пример #3
0
    def make_install_req(ver=None):
        req = Mock()
        req.project_name = test_project_name
        if ver:
            req.url = url_template % str(ver)
            req.specs = [('==', ver)]
        else:
            req.url = url_template.replace('@','') % ''
            req.specs = []

        install_requirement = InstallRequirement(req, None, editable = True, url = req.url)

        return install_requirement
Пример #4
0
    def test_so(self):
        from cmds.so import so
        import urllib2
        socket = Mock()

        self.assertEqual(so(socket, {'arguments': '!so'}),
            'Usage: !so <search term>')
        self.assertEqual(so(socket, {'arguments': '!so  '}),
            'Usage: !so <search term>')

        with patch('stackexchange.Site') as s:
            api = Mock()
            api.search.side_effect = urllib2.HTTPError(code=42, fp=file,
                    url='http://foo', msg='FooError', hdrs='headers')

            s.return_value = api

            self.assertEqual(so(socket, {'arguments': '!so foo'}),
                "The server couldn't fulfill the request!" + \
                        "\r\nReason: FooError\r\nCode: 42")

            api.search.side_effect = None
            api.search.return_value = []
            self.assertEqual(so(socket, {'arguments': '!so foo'}), 'Not found: foo')

            result = Mock()
            result.title = 'foo_title'
            result.url = 'foo_url'
            api.search.return_value = [result]
            self.assertEqual(so(socket, {'arguments': '!so foo'}),
                'foo_title\r\nfoo_url')
Пример #5
0
 def setup_mock_api(cls):
   """Builds up a mock API object, with a mock SchedulerProxy"""
   mock_api = Mock(spec=HookedAuroraClientAPI)
   mock_scheduler = Mock()
   mock_scheduler.url = "http://something_or_other"
   mock_api.scheduler = mock_scheduler
   return (mock_api, mock_scheduler)
Пример #6
0
    def get_signed_grade_mock_request_with_correct_signature(self):
        """
        Generate a proper LTI request object
        """
        mock_request = Mock()
        mock_request.headers = {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': (
                u'OAuth realm="https://testurl/", oauth_body_hash="wwzA3s8gScKD1VpJ7jMt9b%2BMj9Q%3D",'
                'oauth_nonce="18821463", oauth_timestamp="1409321145", '
                'oauth_consumer_key="__consumer_key__", oauth_signature_method="HMAC-SHA1", '
                'oauth_version="1.0", oauth_signature="fHsE1hhIz76/msUoMR3Lyb7Aou4%3D"'
            )
        }
        mock_request.url = u'https://testurl'
        mock_request.http_method = u'POST'
        mock_request.method = mock_request.http_method

        mock_request.body = (
            '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n'
            '<imsx_POXEnvelopeRequest xmlns="http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">'
            '<imsx_POXHeader><imsx_POXRequestHeaderInfo><imsx_version>V1.0</imsx_version>'
            '<imsx_messageIdentifier>edX_fix</imsx_messageIdentifier></imsx_POXRequestHeaderInfo>'
            '</imsx_POXHeader><imsx_POXBody><replaceResultRequest><resultRecord><sourcedGUID>'
            '<sourcedId>MITxLTI/MITxLTI/201x:localhost%3A8000-i4x-MITxLTI-MITxLTI-lti-3751833a214a4f66a0d18f63234207f2:363979ef768ca171b50f9d1bfb322131</sourcedId>'  # pylint: disable=line-too-long
            '</sourcedGUID><result><resultScore><language>en</language><textString>0.32</textString></resultScore>'
            '</result></resultRecord></replaceResultRequest></imsx_POXBody></imsx_POXEnvelopeRequest>'
        )

        return mock_request
Пример #7
0
    def test_unbind(self, mock_gofer_agent):
        context = Mock()
        context.agent_id = "123"
        context.secret = "test-secret"
        context.url = "http://broker.com"
        context.transport = "qpid"
        context.authenticator = Mock()
        context.details = {"task_id": "4567"}
        context.reply_queue = "pulp.task"

        mock_agent = Mock()
        mock_gofer_agent.return_value = mock_agent
        mock_consumer = Mock()
        mock_agent.Consumer = Mock(return_value=mock_consumer)

        bindings = []
        options = {}

        Consumer.unbind(context, bindings, options)

        mock_gofer_agent.assert_called_with(
            context.agent_id,
            ctag=context.reply_queue,
            url=context.url,
            transport=context.transport,
            secret=context.secret,
            authenticator=context.authenticator,
            any=context.details,
        )

        mock_consumer.unbind.assert_called_with(bindings, options)
Пример #8
0
 def topic(self):
     spec = BaseThumbfySpec(key=KEY)
     spec.crypto = Mock(spec=CryptoURL)
     field = Mock()
     field.url = IMAGE_URL
     spec.generate(field)
     return (spec, IMAGE_URL)
Пример #9
0
    def get_signed_grade_mock_request(self, namespace_lti_v1p1=True):
        """
        Example of signed request from LTI Provider.

        When `namespace_v1p0` is set to True then the default namespase from
        LTI 1.1 will be used. Otherwise fake namespace will be added to XML.
        """
        mock_request = Mock()
        mock_request.headers = {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': u'OAuth oauth_nonce="135685044251684026041377608307", \
                oauth_timestamp="1234567890", oauth_version="1.0", \
                oauth_signature_method="HMAC-SHA1", \
                oauth_consumer_key="test_client_key", \
                oauth_signature="my_signature%3D", \
                oauth_body_hash="JEpIArlNCeV4ceXxric8gJQCnBw="'
        }
        mock_request.url = u'http://testurl'
        mock_request.http_method = u'POST'

        params = {}
        if not namespace_lti_v1p1:
            params = {
                'namespace': "http://www.fakenamespace.com/fake"
            }
        mock_request.body = self.get_request_body(params)

        return mock_request
Пример #10
0
    def test_send(self, mock_gofer_agent):
        context = Mock()
        context.agent_id = "123"
        context.url = "http://broker.com"
        context.transport = "qpid"
        context.authenticator = Mock()

        task_id = "5678"
        criteria = {"match": {"task_id": task_id}}

        mock_agent = Mock()
        mock_gofer_agent.return_value = mock_agent
        mock_admin = Mock()
        mock_agent.Admin = Mock(return_value=mock_admin)

        agent = PulpAgent()
        agent.cancel(context, task_id)

        mock_gofer_agent.assert_called_with(
            context.agent_id,
            url=context.url,
            transport=context.transport,
            authenticator=context.authenticator,
            async=True,
        )

        mock_admin.cancel.assert_called_with(criteria=criteria)
Пример #11
0
    def test_download(self, mock_repo_controller, mock_dl_request):
        # Setup
        mock_catalog = Mock()
        mock_catalog.importer_id = 'mock_id'
        mock_catalog.url = 'http://dev.null/'
        mock_catalog.data = {'k': 'v'}
        mock_request = Mock()
        mock_data = {'catalog_entry': mock_catalog, 'client_request': mock_request}
        mock_responder = Mock()
        mock_importer = Mock()
        mock_importer_config = Mock()
        mock_downloader = mock_importer.get_downloader.return_value
        mock_repo_controller.get_importer_by_id.return_value = (mock_importer,
                                                                mock_importer_config)

        # Test
        self.streamer._download(mock_catalog, mock_request, mock_responder)
        mock_repo_controller.get_importer_by_id.assert_called_once_with(mock_catalog.importer_id)
        mock_dl_request.assert_called_once_with(mock_catalog.url, mock_responder, data=mock_data)
        mock_importer.get_downloader.assert_called_once_with(
            mock_importer_config, mock_catalog.url, **mock_catalog.data)
        self.assertEqual(mock_request, mock_downloader.event_listener.request)
        self.assertEqual(self.config, mock_downloader.event_listener.streamer_config)
        mock_downloader.download_one.assert_called_once_with(mock_dl_request.return_value,
                                                             events=True)
        mock_downloader.config.finalize.assert_called_once_with()
Пример #12
0
 def test_is_valid_local_copy(self):
     remote = Mock()
     remote.url = self.url
     repo = Mock()
     repo.remote.return_value = remote
     self.git_mock.Repo.return_value = repo
     self.assertTrue(self.git_manager.is_valid_local_copy)
Пример #13
0
def test_json_response():
    class HTTPError(Exception):
        pass

    response = Mock()
    response.json.return_value = {'a': 1, 'b': {'c': 2, 'd': 3}}
    response.raise_for_status.side_effect = [None, HTTPError()]

    mock = Mock()
    mock.url = "http://example.com"
    mock.http_client.request.return_value = response

    json = JSONResponseProperty(method="POST")
    rv = json.provide_value(mock)

    assert rv == {
        'a': 1,
        'b': {
            'c': 2,
            'd': 3
        }
    }
    response.raise_for_status.assert_called_once_with()
    mock.http_client.request.assert_called_once_with(
        method="POST", url="http://example.com")

    with raises(HTTPError):
        json.provide_value(mock)
Пример #14
0
    def test_unregistered(self, mock_gofer_agent):
        context = Mock()
        context.agent_id = "123"
        context.secret = "test-secret"
        context.url = "http://broker.com"
        context.transport = "qpid"
        context.authenticator = Mock()

        mock_agent = Mock()
        mock_gofer_agent.return_value = mock_agent
        mock_consumer = Mock()
        mock_agent.Consumer = Mock(return_value=mock_consumer)

        # test capability

        Consumer.unregistered(context)

        # validation

        mock_gofer_agent.assert_called_with(
            context.agent_id,
            url=context.url,
            secret=context.secret,
            authenticator=context.authenticator,
            transport=context.transport,
            async=True,
        )

        mock_consumer.unregistered.assert_called_with()
Пример #15
0
    def test_auth_header_preserved_from_s3_redirects(self):
        request = AWSRequest()
        request.url = 'https://bucket.s3.amazonaws.com/'
        request.method = 'GET'
        request.headers['Authorization'] = 'original auth header'
        prepared_request = request.prepare()

        fake_response = Mock()
        fake_response.headers = {
            'location': 'https://bucket.s3-us-west-2.amazonaws.com'}
        fake_response.url = request.url
        fake_response.status_code = 307
        fake_response.is_permanent_redirect = False
        # This line is needed to disable the cookie handling
        # code in requests.
        fake_response.raw._original_response = None

        success_response = Mock()
        success_response.raw._original_response = None
        success_response.is_redirect = False
        success_response.status_code = 200
        session = PreserveAuthSession()
        session.send = Mock(return_value=success_response)

        list(session.resolve_redirects(
            fake_response, prepared_request, stream=False))

        redirected_request = session.send.call_args[0][0]
        # The Authorization header for the newly sent request should
        # still have our original Authorization header.
        self.assertEqual(
            redirected_request.headers['Authorization'],
            'original auth header')
Пример #16
0
    def test_list_packages_filters(self):
        """
        The package list must be stripped from inherited packages and [*redirected] messages
        """
        devpi_listing = [
            '*redirected: http://localhost:2414/user/index2/delete_me',
            'http://localhost:2414/user/index2/+f/70e/3bc67b3194143/delete_me-0.2-py2.py3-none-any.whl',
            'http://localhost:2414/user/index2/+f/313/8642d2b43a764/delete_me-0.2.tar.gz',
            'http://localhost:2414/other_user/index1/+f/70e/3bc67b3194143/delete_me-0.2-py2.py3-none-any.whl',
            'http://localhost:2414/other_user/index1/+f/313/8642d2b43a764/delete_me-0.2.tar.gz'
        ]
        expected_packages = {
            'user/index2': {Package(devpi_listing[1])}
        }

        devpi_client = Mock(spec=DevpiCommandWrapper)
        devpi_client.user = 'user'
        devpi_client.url = 'http://localhost:2414/user/index2'
        devpi_client.list_indices.return_value = ['user/index2']
        devpi_client.list.return_value = devpi_listing

        actual_packages = list_packages_by_index(devpi_client, 'user', 'delete_me', only_dev=False, version_filter=None)
        self.assertDictEqual(expected_packages, actual_packages)

        devpi_client.list.assert_called_once_with('--index', 'user/index2', '--all', 'delete_me')  # `--all` is important as otherwise not all packages will be returned
Пример #17
0
def get_mock_no_oembed():
    mock = Mock()
    mock.status_code = youtube_status_code
    mock.url = youtube_url
    mock.cookies = youtube_cookies
    mock.text = 'youtube_text'
    mock.json = lambda: json.loads(mock.text)
    return [mock]
Пример #18
0
def fake_app_patch(test_case):
    project = create_project("myproject")
    app_config = create_app_config(project, "my_app")
    app = Mock()
    app.__version__ = "0"
    app.config = app_config
    app.url = "/-app-/"
    return patch.object(c, "app", app, create=True)
Пример #19
0
def fake_app_patch(test_case):
    project = create_project('myproject')
    app_config = create_app_config(project, 'my_app')
    app = Mock()
    app.__version__ = '0'
    app.config = app_config
    app.url = '/-app-/'
    return patch.object(c, 'app', app, create=True)
    def test_check_connection_should_return_true_when_link_is_up(self):
        mock_broadcaster = Mock(WampBroadcaster)
        mock_broadcaster.logger = Mock()
        mock_broadcaster.url = "ws://broadcaster"
        mock_broadcaster.client = Mock()

        self.assertEqual(WampBroadcaster._check_connection(mock_broadcaster), True)
        self.assertFalse(hasattr(mock_broadcaster, "not_connected_warning_sent"))
 def test_login_failed_cookie(self, post):
     login_result = Mock()
     login_result.url = 'http://rutracker.org/forum/index.php'
     post.return_value = login_result
     with self.assertRaises(FreeTorrentsLoginFailedException) as e:
         self.tracker.login(self.helper.fake_login, self.helper.fake_password)
     self.assertEqual(e.exception.code, 2)
     self.assertEqual(e.exception.message, 'Failed to retrieve cookie')
Пример #22
0
def test_get_http_auth_credentials_acl(auth_mock):
    m = Mock()
    m.url = 'http://domain.com'
    m.headers = {'www-authenticate': 'acsjwt"'}
    auth_mock.return_value = ("username", "password")

    returned_auth = http._get_http_auth(m, urlparse(m.url), "acsjwt")
    assert type(returned_auth) == http.DCOSAcsAuth
Пример #23
0
def test_get_http_auth_credentials_good_reponse(auth_mock):
    m = Mock()
    m.url = 'http://domain.com'
    m.headers = {'www-authenticate': 'Basic realm="Restricted"'}
    auth = HTTPBasicAuth("username", "password")
    auth_mock.return_value = auth

    returned_auth = http._get_http_auth_credentials(m)
    assert returned_auth == auth
Пример #24
0
 def test_is_valid_local_returns_false_if_url_mismatch(self):
     fake_url = self.url + 'not_the_same'
     remote = Mock()
     remote.url = fake_url
     repo = Mock()
     repo.remote.return_value = remote
     self.git_mock.Repo.return_value = repo
     git_manager = GitManager(self.url, self.dst_path)
     self.assertFalse(git_manager.is_valid_local_copy)
 def _get_fake_repo(self, name, repo_id, url, number_of_stars, number_of_forks, number_of_pull_requests):
     repo = Mock(Repo)
     repo.name = name
     repo.repo_id = repo_id
     repo.url = url
     repo.number_of_stars = number_of_stars
     repo.number_of_forks = number_of_forks
     repo.pull_requests = [{}] * number_of_pull_requests
     return repo
Пример #26
0
    def test_calculate_resource_relative_api(self):
        '''This test case ensures an url is correctly built when roa_api is hosted on the same domain as the project.'''

        resource = Mock()
        resource.url = "/sample-resources"

        roa_api = "/api"

        self.assertEqual("/api/1.0%s" % resource.url, roa_helper.calculate_resource_url(roa_api, resource, 1.0))
Пример #27
0
 def test_sites_block(self):
     site = Mock()
     site.url = 'http://youtube.com'
     ms = [site]
     req = self.factory.get('/')
     req.mobile_site = False
     r = render('{{ sites_block(ms, 100) }}', dict(ms=ms, request=req))
     doc = pq(r)
     eq_(doc('strong').text(), 'youtube.com')
Пример #28
0
def reqlib(url):
    reqlib = Mock(name="requests")
    response = Mock(name="response")
    response.url = url
    reqlib.get.return_value = response

    r = reqlib.get(url)
    assert r.url == url
    return reqlib
Пример #29
0
    def test_calculate_resource_abs_api(self):
        '''This test case ensures an url is correctly built when roa_api is hosted on a separate domain than the project.'''

        resource = Mock()
        resource.url = "/sample-resources"

        roa_api = "https://api.fantastico.com/roa/api"

        self.assertEqual("https://api.fantastico.com/roa/api/2.0%s" % resource.url,
                         roa_helper.calculate_resource_url(roa_api, resource, 2.0))
Пример #30
0
def test_get_http_auth_credentials_basic(auth_mock):
    m = Mock()
    m.url = 'http://domain.com'
    m.headers = {'www-authenticate': 'Basic realm="Restricted"'}
    auth_mock.return_value = ("username", "password")

    returned_auth = http._get_http_auth(m, urlparse(m.url), "basic")
    assert type(returned_auth) == HTTPBasicAuth
    assert returned_auth.username == "username"
    assert returned_auth.password == "password"