Exemplo n.º 1
0
    def test_valid_session_id_invalid_data(self, pyramid_request):
        pyramid_request.cookies["session_id"] = "123456"

        session_factory = SessionFactory(
            "mysecret", "redis://redis://localhost:6379/0",
        )
        session_factory.signer.unsign = pretend.call_recorder(
            lambda session_id, max_age: b"123456"
        )
        session_factory.redis = pretend.stub(
            get=pretend.call_recorder(lambda key: b"invalid data"),
        )
        session_factory._process_response = pretend.stub()
        session = session_factory(pyramid_request)

        assert len(pyramid_request.response_callbacks) == 1
        assert pyramid_request.response_callbacks[0] is \
            session_factory._process_response

        assert session_factory.signer.unsign.calls == [
            pretend.call("123456", max_age=12 * 60 * 60),
        ]

        assert session_factory.redis.get.calls == [
            pretend.call("warehouse/session/data/123456"),
        ]

        assert isinstance(session, Session)
        assert session._sid is None
        assert session.new
Exemplo n.º 2
0
    def test_csp_policy(self):
        response = pretend.stub(headers={})
        handler = pretend.call_recorder(lambda request: response)
        settings = {
            "csp": {
                "default-src": ["*"],
                "style-src": ["'self'", "example.net"],
            },
        }
        registry = pretend.stub(settings=settings)

        tween = csp.content_security_policy_tween_factory(handler, registry)

        request = pretend.stub(
            path="/project/foobar/",
            find_service=pretend.call_recorder(
                lambda *args, **kwargs: settings["csp"]
            ),
        )

        assert tween(request) is response
        assert response.headers == {
            "Content-Security-Policy":
                "default-src *; style-src 'self' example.net",
        }
Exemplo n.º 3
0
    def test_devel_csp(self):
        settings = {
            "csp": {
                "script-src": ["{request.scheme}://{request.host}"],
            }
        }
        response = pretend.stub(headers={})
        registry = pretend.stub(settings=settings)
        handler = pretend.call_recorder(lambda request: response)

        tween = csp.content_security_policy_tween_factory(handler, registry)

        request = pretend.stub(
            scheme="https",
            host="example.com",
            path="/path/to/nowhere",
            find_service=pretend.call_recorder(
                lambda *args, **kwargs: settings["csp"],
            ),
        )

        assert tween(request) is response
        assert response.headers == {
            "Content-Security-Policy": "script-src https://example.com",
        }
Exemplo n.º 4
0
    def test_invalidated_deletes_no_save(self, pyramid_request):
        session_factory = SessionFactory(
            "mysecret", "redis://redis://localhost:6379/0",
        )
        session_factory.redis = pretend.stub(
            delete=pretend.call_recorder(lambda key: None)
        )
        pyramid_request.session.invalidated = ["1", "2"]
        pyramid_request.session.should_save = pretend.call_recorder(
            lambda: False
        )
        response = pretend.stub(
            delete_cookie=pretend.call_recorder(lambda cookie: None),
        )
        session_factory._process_response(pyramid_request, response)

        assert session_factory.redis.delete.calls == [
            pretend.call("warehouse/session/data/1"),
            pretend.call("warehouse/session/data/2"),
        ]
        assert pyramid_request.session.should_save.calls == [
            pretend.call(),
            pretend.call(),
        ]
        assert response.delete_cookie.calls == [pretend.call("session_id")]
Exemplo n.º 5
0
    def test_csp_policy_inject(self):
        response = pretend.stub(headers={})

        def handler(request):
            request.find_service("csp")["default-src"].append("example.com")
            return response

        settings = {
            "csp": {
                "default-src": ["*"],
                "style-src": ["'self'"],
            },
        }

        registry = pretend.stub(settings=settings)
        tween = csp.content_security_policy_tween_factory(handler, registry)

        request = pretend.stub(
            path="/example",
            find_service=pretend.call_recorder(
                lambda *args, **kwargs: settings["csp"]
            ),
        )

        assert tween(request) is response
        assert response.headers == {
            "Content-Security-Policy":
                "default-src * example.com; style-src 'self'",
        }
Exemplo n.º 6
0
def test_mime_content_serialize_xml():
    wsdl = stub(schema=stub(_prefix_map={}))
    operation = stub(location='my-action', name='foo')

    element_1 = xsd.Element('arg1', xsd.ComplexType([
        xsd.Element('arg1_1', xsd.String())
    ]))
    element_2 = xsd.Element('arg2', xsd.String())
    abstract_message = definitions.AbstractMessage(
        etree.QName('{http://test.python-zeep.org/tests/msg}Method'))
    abstract_message.parts = OrderedDict([
        ('xarg1', definitions.MessagePart(element=element_1, type=None)),
        ('xarg2', definitions.MessagePart(element=element_2, type=None)),
    ])

    msg = messages.MimeContent(
        wsdl=wsdl, name=None, operation=operation, content_type='text/xml',
        part_name=None)

    msg._info = {
        'body': {'namespace': 'http://test.python-zeep.org/tests/rpc'},
        'header': None,
        'headerfault': None
    }
    msg.resolve(wsdl, abstract_message)

    serialized = msg.serialize(xarg1={'arg1_1': 'uh'}, xarg2='bla')
    assert serialized.headers == {
        'Content-Type': 'text/xml'
    }
    assert serialized.path == 'my-action'
    assert_nodes_equal(
        load_xml(serialized.content),
        load_xml(
            "<foo><xarg1><arg1_1>uh</arg1_1></xarg1><xarg2>bla</xarg2></foo>"))
Exemplo n.º 7
0
    def test_without_a_query(self, monkeypatch, db_request, page):
        params = MultiDict()
        if page is not None:
            params["page"] = page
        db_request.params = params

        es_query = pretend.stub()
        db_request.es = pretend.stub(query=lambda *a, **kw: es_query)

        page_obj = pretend.stub(page_count=(page or 1) + 10)
        page_cls = pretend.call_recorder(lambda *a, **kw: page_obj)
        monkeypatch.setattr(views, "ElasticsearchPage", page_cls)

        url_maker = pretend.stub()
        url_maker_factory = pretend.call_recorder(lambda request: url_maker)
        monkeypatch.setattr(views, "paginate_url_factory", url_maker_factory)

        assert search(db_request) == {
            "page": page_obj,
            "term": params.get("q", ''),
            "order": params.get("o", ''),
            "applied_filters": [],
            "available_filters": [],
        }
        assert page_cls.calls == [
            pretend.call(es_query, url_maker=url_maker, page=page or 1),
        ]
        assert url_maker_factory.calls == [pretend.call(db_request)]
Exemplo n.º 8
0
def test_rpc_message_serializer(abstract_message_input):
    wsdl = stub(schema=stub(_prefix_map={}))
    operation = stub(soapaction='my-action')

    msg = messages.RpcMessage(
        wsdl=wsdl,
        name=None,
        operation=operation,
        nsmap=soap.Soap11Binding.nsmap)

    msg._info = {
        'body': {
            'namespace': 'http://test.python-zeep.org/tests/rpc',
        },
        'header': None,
        'headerfault': None
    }
    msg.resolve(wsdl, abstract_message_input)

    serialized = msg.serialize(arg1='ah1', arg2='ah2')
    expected = """
        <?xml version="1.0"?>
        <soap-env:Envelope
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
          <soap-env:Body>
            <ns0:Method xmlns:ns0="http://test.python-zeep.org/tests/rpc">
              <arg1>ah1</arg1>
              <arg2>ah2</arg2>
            </ns0:Method>
          </soap-env:Body>
        </soap-env:Envelope>
    """
    assert_nodes_equal(expected, serialized.content)
Exemplo n.º 9
0
def test_rpc_message_deserializer(abstract_message_output):
    response_body = load_xml("""
        <SOAP-ENV:Body
            xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <mns:Response xmlns:mns="http://test.python-zeep.org/tests/rpc"
                SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
            <result xsi:type="xsd:string">foobar</result>
          </mns:Response>
        </SOAP-ENV:Body>
    """)  # noqa
    wsdl = stub(schema=stub(_prefix_map={}))
    operation = stub(soapaction='my-action')

    msg = messages.RpcMessage(
        wsdl=wsdl,
        name=None,
        operation=operation,
        nsmap=soap.Soap11Binding.nsmap)

    msg._info = {
        'body': {'namespace': 'http://test.python-zeep.org/tests/rpc'},
        'header': None,
        'headerfault': None
    }
    msg.resolve(wsdl, abstract_message_output)

    result = msg.deserialize(response_body)
    assert result == 'foobar'
Exemplo n.º 10
0
def test_document_message_parse():
    xmlelement = load_xml("""
      <input
            xmlns="http://schemas.xmlsoap.org/wsdl/"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
        <soap:body use="literal"/>
      </input>
    """)

    operation = stub()
    definitions_ = stub(
        target_namespace='',
        messages={},
        wsdl=stub())

    msg = messages.DocumentMessage.parse(
        definitions=definitions_,
        xmlelement=xmlelement,
        operation=operation,
        nsmap={})

    abstract_body = definitions.AbstractMessage(
        etree.QName('{http://test.python-zeep.org/tests/msg}Input'))
    abstract_body.parts['params'] = definitions.MessagePart(
        element=xsd.Element(etree.QName('input'), xsd.String()),
        type=None)

    msg.resolve(definitions_, abstract_body)

    assert msg.headerfault is None
    assert msg.header is None
    assert msg.body == abstract_body.parts['params'].element
Exemplo n.º 11
0
def test_rpc_message_parse():
    xmlelement = load_xml("""
      <input
            xmlns="http://schemas.xmlsoap.org/wsdl/"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
        <soap:body use="encoded" namespace="http://tests.python-zeep.org/rpc"
                   encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
      </input>
    """)

    operation = stub()
    definitions_ = stub(
        target_namespace='',
        messages={},
        wsdl=stub())

    msg = messages.RpcMessage.parse(
        definitions=definitions_,
        xmlelement=xmlelement,
        operation=operation,
        nsmap={})

    abstract_body = definitions.AbstractMessage(
        etree.QName('{http://test.python-zeep.org/tests/msg}Input'))
    abstract_body.parts['arg1'] = definitions.MessagePart(
        element=None, type=xsd.String())
    abstract_body.parts['arg2'] = definitions.MessagePart(
        element=None, type=xsd.String())

    msg.resolve(definitions_, abstract_body)

    assert msg.headerfault is None
    assert msg.header is None
    assert msg.body is not None
Exemplo n.º 12
0
def test_includeme(monkeypatch):
    authn_obj = pretend.stub()
    authn_cls = pretend.call_recorder(lambda callback: authn_obj)
    authz_obj = pretend.stub()
    authz_cls = pretend.call_recorder(lambda: authz_obj)
    monkeypatch.setattr(accounts, "SessionAuthenticationPolicy", authn_cls)
    monkeypatch.setattr(accounts, "ACLAuthorizationPolicy", authz_cls)

    config = pretend.stub(
        register_service_factory=pretend.call_recorder(
            lambda factory, iface: None
        ),
        add_request_method=pretend.call_recorder(lambda f, name, reify: None),
        set_authentication_policy=pretend.call_recorder(lambda p: None),
        set_authorization_policy=pretend.call_recorder(lambda p: None),
    )

    accounts.includeme(config)

    config.register_service_factory.calls == [
        pretend.call(database_login_factory, IUserService),
    ]
    config.add_request_method.calls == [
        pretend.call(accounts._user, name="user", reify=True),
    ]
    config.set_authentication_policy.calls == [pretend.call(authn_obj)]
    config.set_authorization_policy.calls == [pretend.call(authz_obj)]
    authn_cls.calls == [pretend.call(callback=accounts._authenticate)]
    authz_cls.calls == [pretend.call()]
Exemplo n.º 13
0
    def test_with_valid_password(self, monkeypatch):
        principals = pretend.stub()
        authenticate = pretend.call_recorder(
            lambda userid, request: principals
        )
        monkeypatch.setattr(accounts, "_authenticate", authenticate)

        userid = pretend.stub()
        service = pretend.stub(
            find_userid=pretend.call_recorder(lambda username: userid),
            check_password=pretend.call_recorder(
                lambda userid, password: True
            ),
        )
        request = pretend.stub(
            find_service=pretend.call_recorder(lambda iface, context: service),
        )

        assert accounts._login("myuser", "mypass", request) is principals
        assert request.find_service.calls == [
            pretend.call(IUserService, context=None),
        ]
        assert service.find_userid.calls == [pretend.call("myuser")]
        assert service.check_password.calls == [pretend.call(userid, "mypass")]
        assert authenticate.calls == [pretend.call(userid, request)]
Exemplo n.º 14
0
def test_wsgi_app_exception(app, monkeypatch):
    match = pretend.stub(match=pretend.call_recorder(lambda: ("warehouse.fake.view", {})))
    urls = pretend.stub(bind_to_environ=pretend.call_recorder(lambda e: match))
    response = pretend.call_recorder(lambda e, s: None)

    class FakeException(HTTPException):

        # @pretend.call_recorder
        def __call__(self, *args, **kwargs):
            return response

    @pretend.call_recorder
    def fake_view(*args, **kwargs):
        raise FakeException("An error has occurred")

    fake_module = pretend.stub(view=fake_view)
    import_module = pretend.call_recorder(lambda mod: fake_module)

    monkeypatch.setattr(importlib, "import_module", import_module)

    environ = create_environ()
    start_response = pretend.stub()

    app.urls = urls

    app.wsgi_app(environ, start_response)

    assert match.match.calls == [pretend.call()]
    assert urls.bind_to_environ.calls == [pretend.call(environ)]
    assert import_module.calls == [pretend.call("warehouse.fake")]
    assert fake_view.calls == [pretend.call(app, mock.ANY)]
Exemplo n.º 15
0
def stub_db_connect_database_interaction(results=[]):
    """Stub out the ``cnxarchive.database.db_connect`` function
    and child functions for simple interactions.

    The interactions look something like::

        >>> with db_connect() as db_conn:
        ...     with db_conn.cursor() as cursor:
        ...         cursor.execute(...)
        ...         results = cursor.fetchall()

    """
    # Stub the database interaction
    cursor = pretend.stub(
        execute=lambda *a, **kw: None,
        fetchall=lambda: results,
    )
    cursor_contextmanager = pretend.stub(
        __enter__=lambda *a: cursor,
        __exit__=lambda a, b, c: None,
    )
    db_conn = pretend.stub(cursor=lambda **kw: cursor_contextmanager)
    db_connect_contextmanager = pretend.stub(
        __enter__=lambda: db_conn,
        __exit__=lambda a, b, c: None,
    )
    db_connect = pretend.stub(
        __call__=lambda: db_connect_contextmanager,
    )
    return db_connect
Exemplo n.º 16
0
    def test_send_email_success(self, monkeypatch):
        message_obj = Message()

        def mock_message(*args, **kwargs):
            return message_obj

        monkeypatch.setattr(email, "Message", mock_message)

        task = pretend.stub()
        mailer = pretend.stub(
            send_immediately=pretend.call_recorder(lambda i: None)
        )
        request = pretend.stub(
            registry=pretend.stub(
                settings=pretend.stub(
                    get=pretend.call_recorder(lambda k: 'SENDER'),
                ),
                getUtility=pretend.call_recorder(lambda mailr: mailer)
            )
        )

        email.send_email(
            task,
            request,
            "body",
            "subject",
            recipients=["recipients"],
        )

        assert mailer.send_immediately.calls == [pretend.call(message_obj)]
        assert request.registry.getUtility.calls == [pretend.call(IMailer)]
        assert request.registry.settings.get.calls == [
            pretend.call("mail.sender")]
Exemplo n.º 17
0
def test_calling_application_is_wsgi_app(app):
    app.wsgi_app = pretend.call_recorder(lambda e, s: None)

    environ, start_response = pretend.stub(), pretend.stub()
    app(environ, start_response)

    assert app.wsgi_app.calls == [pretend.call(environ, start_response)]
Exemplo n.º 18
0
    def test_with_user(self, is_superuser, is_moderator, expected):
        user = pretend.stub(is_superuser=is_superuser, is_moderator=is_moderator)
        service = pretend.stub(get_user=pretend.call_recorder(lambda userid: user))
        request = pretend.stub(find_service=lambda iface, context: service)

        assert accounts._authenticate(1, request) == expected
        assert service.get_user.calls == [pretend.call(1)]
Exemplo n.º 19
0
    def test_with_disabled_user_compromised_pw(self, pyramid_request, pyramid_services):
        user = pretend.stub(id=1)
        service = pretend.stub(
            get_user=pretend.call_recorder(lambda user_id: user),
            find_userid=pretend.call_recorder(lambda username: 1),
            check_password=pretend.call_recorder(
                lambda userid, password, tags=None: False
            ),
            is_disabled=pretend.call_recorder(
                lambda user_id: (True, DisableReason.CompromisedPassword)
            ),
        )
        pyramid_services.register_service(IUserService, None, service)
        pyramid_services.register_service(
            IPasswordBreachedService,
            None,
            pretend.stub(failure_message_plain="Bad Password!"),
        )

        with pytest.raises(BasicAuthBreachedPassword) as excinfo:
            assert (
                accounts._basic_auth_login("myuser", "mypass", pyramid_request) is None
            )

        assert excinfo.value.status == "401 Bad Password!"
        assert service.find_userid.calls == [pretend.call("myuser")]
        assert service.get_user.calls == [pretend.call(1)]
        assert service.is_disabled.calls == [pretend.call(1)]
        assert service.check_password.calls == []
Exemplo n.º 20
0
    def test_call(self, monkeypatch):
        request = pretend.stub()
        registry = pretend.stub()
        result = pretend.stub()

        prepared = {
            "registry": registry,
            "request": request,
            "closer": pretend.call_recorder(lambda: None)
        }
        prepare = pretend.call_recorder(lambda *a, **kw: prepared)
        monkeypatch.setattr(scripting, "prepare", prepare)

        @pretend.call_recorder
        def runner(irequest):
            assert irequest is request
            return result

        task = celery.WarehouseTask()
        task.app = Celery()
        task.app.pyramid_config = pretend.stub(registry=registry)
        task.run = runner

        assert task() is result
        assert prepare.calls == [pretend.call(registry=registry)]
        assert prepared["closer"].calls == [pretend.call()]
        assert runner.calls == [pretend.call(request)]
Exemplo n.º 21
0
    def test_request_without_tm(self, monkeypatch):
        async_result = pretend.stub()
        super_class = pretend.stub(
            apply_async=pretend.call_recorder(lambda *a, **kw: async_result),
        )
        real_super = __builtins__["super"]
        inner_super = pretend.call_recorder(lambda *a, **kw: super_class)

        def fake_super(*args, **kwargs):
            if not args and not kwargs:
                return inner_super(*args, **kwargs)
            else:
                return real_super(*args, **kwargs)

        monkeypatch.setitem(__builtins__, "super", fake_super)

        request = pretend.stub()
        get_current_request = pretend.call_recorder(lambda: request)
        monkeypatch.setattr(celery, "get_current_request", get_current_request)

        task = celery.WarehouseTask()
        task.app = Celery()

        assert task.apply_async() is async_result

        assert super_class.apply_async.calls == [pretend.call()]
        assert get_current_request.calls == [pretend.call()]
        assert inner_super.calls == [pretend.call()]
Exemplo n.º 22
0
    def test_after_commit_hook(self, monkeypatch, success):
        args = [pretend.stub(), pretend.stub()]
        kwargs = {"foo": pretend.stub(), "bar": pretend.stub()}

        super_class = pretend.stub(
            apply_async=pretend.call_recorder(lambda *a, **kw: None),
        )
        real_super = __builtins__["super"]
        inner_super = pretend.call_recorder(lambda *a, **kw: super_class)

        def fake_super(*args, **kwargs):
            if not args and not kwargs:
                return inner_super(*args, **kwargs)
            else:
                return real_super(*args, **kwargs)

        monkeypatch.setitem(__builtins__, "super", fake_super)

        task = celery.WarehouseTask()
        task.app = Celery()
        task._after_commit_hook(success, *args, **kwargs)

        if success:
            assert inner_super.calls == [pretend.call()]
        else:
            assert inner_super.calls == []
Exemplo n.º 23
0
def test_vary_by(varies, expected):
    view = lambda app, request: Response("")

    for vary in varies:
        view = vary_by(*vary)(view)

    assert view(pretend.stub(), pretend.stub()).vary.as_set() == expected
Exemplo n.º 24
0
 def test_copy_backend_object(self):
     backend = DummyHashBackend([hashes.SHA1])
     copied_ctx = pretend.stub()
     pretend_ctx = pretend.stub(copy=lambda: copied_ctx)
     h = hashes.Hash(hashes.SHA1(), backend=backend, ctx=pretend_ctx)
     assert h._backend is backend
     assert h.copy()._backend is h._backend
Exemplo n.º 25
0
    def test_404_when_missing_file(self, db_request, pyramid_config):
        @pretend.call_recorder
        def raiser(path):
            raise FileNotFoundError

        storage_service = pretend.stub(get=raiser)

        project = ProjectFactory.create()
        release = ReleaseFactory.create(project=project)
        file_ = FileFactory.create(
            release=release,
            filename="{}-{}.tar.gz".format(project.name, release.version),
            python_version="source",
        )

        path = "source/{}/{}/{}".format(
            project.name[0], project.name, file_.filename
        )

        db_request.matchdict["path"] = path
        db_request.log = pretend.stub(
            error=pretend.call_recorder(lambda event, **kw: None),
        )
        db_request.find_service = pretend.call_recorder(
            lambda iface: storage_service
        )

        resp = views.packages(db_request)

        assert isinstance(resp, HTTPNotFound)
        assert db_request.find_service.calls == [pretend.call(IFileStorage)]
        assert storage_service.get.calls == [pretend.call(path)]
        assert db_request.log.error.calls == [
            pretend.call("missing file data", path=path),
        ]
Exemplo n.º 26
0
    def test_service_creation(self, monkeypatch):
        crypt_context_obj = pretend.stub()
        crypt_context_cls = pretend.call_recorder(
            lambda **kwargs: crypt_context_obj
        )
        monkeypatch.setattr(services, "CryptContext", crypt_context_cls)

        session = pretend.stub()
        service = services.DatabaseUserService(session)

        assert service.db is session
        assert service.hasher is crypt_context_obj
        assert crypt_context_cls.calls == [
            pretend.call(
                schemes=[
                    "argon2",
                    "bcrypt_sha256",
                    "bcrypt",
                    "django_bcrypt",
                    "unix_disabled",
                ],
                deprecated=["auto"],
                truncate_error=True,
                argon2__memory_cost=1024,
                argon2__parallelism=6,
                argon2__time_cost=6,
            ),
        ]
Exemplo n.º 27
0
 def test_get_plate_umpire(self):
     attrib = {"position": "home", "name": "Gerry Davis"}
     expected = {"name": "Gerry Davis"}
     element = stub(attrib=attrib)
     tree = stub(findall=lambda arg: [element])
     actual = parser.get_plate_umpire(tree)
     self.assertEqual(actual, expected)
Exemplo n.º 28
0
    def test_camoify_no_src(self, monkeypatch):
        html = "<img>"

        request = pretend.stub(
            registry=pretend.stub(
                settings={
                    "camo.url": "https://camo.example.net/",
                    "camo.key": "fake key",
                },
            ),
        )
        camo_url = partial(filters._camo_url, request)
        request.camo_url = camo_url

        ctx = {"request": request}

        gen_camo_url = pretend.call_recorder(
            lambda curl, ckey, url: "https://camo.example.net/image.jpg"
        )
        monkeypatch.setattr(filters, "_camo_url", gen_camo_url)

        result = filters.camoify(ctx, html)

        assert result == "<img>"
        assert gen_camo_url.calls == []
Exemplo n.º 29
0
def test_includeme(monkeypatch):
    session_factory_obj = pretend.stub()
    session_factory_cls = pretend.call_recorder(
        lambda secret, url: session_factory_obj
    )
    monkeypatch.setattr(
        warehouse.sessions,
        "SessionFactory",
        session_factory_cls,
    )

    config = pretend.stub(
        set_session_factory=pretend.call_recorder(lambda factory: None),
        registry=pretend.stub(
            settings={
                "sessions.secret": "my secret",
                "sessions.url": "my url",
            },
        ),
        add_view_deriver=pretend.call_recorder(lambda *a, **kw: None),
    )

    includeme(config)

    assert config.set_session_factory.calls == [
        pretend.call(session_factory_obj),
    ]
    assert session_factory_cls.calls == [pretend.call("my secret", "my url")]
    assert config.add_view_deriver.calls == [
        pretend.call(
            session_view,
            over="csrf_view",
            under=viewderivers.INGRESS,
        ),
    ]
Exemplo n.º 30
0
def test_includeme(monkeypatch, env, ssl):
    app = pretend.stub(conf={})
    monkeypatch.setattr(celery, "app", app)

    config = pretend.stub(
        registry=pretend.stub(
            settings={
                "warehouse.env": env,
                "celery.broker_url": pretend.stub(),
                "celery.result_url": pretend.stub(),
            },
        ),
    )
    celery.includeme(config)

    assert app.pyramid_config is config
    assert app.conf == {
        "BROKER_URL": config.registry.settings["celery.broker_url"],
        "BROKER_USE_SSL": ssl,
        "CELERY_DISABLE_RATE_LIMITS": True,
        "CELERY_RESULT_BACKEND": config.registry.settings["celery.result_url"],
        "CELERY_RESULT_SERIALIZER": "json",
        "CELERY_TASK_SERIALIZER": "json",
        "CELERY_ACCEPT_CONTENT": ["json", "msgpack"],
        "CELERY_MESSAGE_COMPRESSION": "gzip",
        "CELERY_QUEUE_HA_POLICY": "all",
    }
Exemplo n.º 31
0
 def test_skip_regex_no_skip_option(self):
     options = stub(skip_requirements_regex=None)
     line = '--extra-index-url Good'
     assert [(0, line)] == list(skip_regex(enumerate([line]), options))
Exemplo n.º 32
0
    def test_version_search(self):
        class FakeQuery:
            def __init__(self, type, must):
                self.type = type
                self.must = must

            def __getitem__(self, name):
                self.offset = name.start
                self.limit = name.stop
                self.step = name.step
                return self

            def execute(self):
                assert self.type == "bool"
                assert [q.to_dict() for q in self.must] == [
                    {
                        "term": {
                            "name": "foo"
                        }
                    },
                    {
                        "term": {
                            "version": "1.0"
                        }
                    },
                ]
                assert self.offset is None
                assert self.limit == 1000
                assert self.step is None
                return [
                    pretend.stub(
                        name="foo",
                        summary="my summary",
                        latest_version="1.0",
                        version=["1.0"],
                    ),
                    pretend.stub(
                        name="foo-bar",
                        summary="other summary",
                        latest_version="2.0",
                        version=["2.0", "1.0"],
                    ),
                ]

        request = pretend.stub(
            es=pretend.stub(query=FakeQuery),
            registry=pretend.stub(datadog=pretend.stub(
                histogram=lambda *a, **kw: None,
            ), ),
        )
        results = xmlrpc.search(
            request,
            {
                "name": "foo",
                "version": "1.0"
            },
            "and",
        )
        assert results == [
            {
                "_pypi_ordering": False,
                "name": "foo",
                "summary": "my summary",
                "version": "1.0"
            },
            {
                "_pypi_ordering": False,
                "name": "foo-bar",
                "summary": "other summary",
                "version": "1.0"
            },
        ]
Exemplo n.º 33
0
    def test_fails_with_invalid_operator(self):
        with pytest.raises(xmlrpc.XMLRPCWrappedError) as exc:
            xmlrpc.search(pretend.stub(), {}, "lol nope")

        assert exc.value.faultString == \
            "ValueError: Invalid operator, must be one of 'and' or 'or'."
Exemplo n.º 34
0
    def test_default_search_operator_with_spaces_in_values(self):
        class FakeQuery:
            def __init__(self, type, must):
                self.type = type
                self.must = must

            def __getitem__(self, name):
                self.offset = name.start
                self.limit = name.stop
                self.step = name.step
                return self

            def execute(self):
                assert self.type == "bool"
                assert [q.to_dict() for q in self.must] == [{
                    'bool': {
                        'should': [{
                            'term': {
                                'summary': 'fix code'
                            }
                        }, {
                            'term': {
                                'summary': 'like this'
                            }
                        }]
                    }
                }]
                assert self.offset is None
                assert self.limit == 1000
                assert self.step is None
                return [
                    pretend.stub(
                        name="foo",
                        summary="fix code",
                        latest_version="1.0",
                        version=["1.0"],
                    ),
                    pretend.stub(
                        name="foo-bar",
                        summary="like this",
                        latest_version="2.0",
                        version=["2.0", "1.0"],
                    ),
                ]

        request = pretend.stub(
            es=pretend.stub(query=FakeQuery),
            registry=pretend.stub(datadog=pretend.stub(
                histogram=lambda *a, **kw: None,
            ), ),
        )
        results = xmlrpc.search(
            request,
            {"summary": ["fix code", "like this"]},
        )
        assert results == [
            {
                "_pypi_ordering": False,
                "name": "foo",
                "summary": "fix code",
                "version": "1.0"
            },
            {
                "_pypi_ordering": False,
                "name": "foo-bar",
                "summary": "like this",
                "version": "2.0"
            },
        ]
Exemplo n.º 35
0
 def test_edit_project_button_returns_project(self):
     project = pretend.stub()
     assert views.edit_project_button(project, pretend.stub()) == {
         'project': project
     }
Exemplo n.º 36
0
def test_require_wsa(recwarn, monkeypatch):
    monkeypatch.setattr(
        uuid, 'uuid4',
        lambda: uuid.UUID('ada686f9-5995-4088-bea4-239f694b2eaf'))

    wsdl_main = StringIO("""
        <?xml version="1.0"?>
        <wsdl:definitions
          xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          xmlns:tns="http://tests.python-zeep.org/xsd-main"
          xmlns:sec="http://tests.python-zeep.org/wsdl-secondary"
          xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
          xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl"
          xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/"
          targetNamespace="http://tests.python-zeep.org/xsd-main">
          <wsdl:types>
            <xsd:schema
                targetNamespace="http://tests.python-zeep.org/xsd-main"
                xmlns:tns="http://tests.python-zeep.org/xsd-main">
              <xsd:element name="input" type="xsd:string"/>
              <xsd:element name="input2" type="xsd:string"/>
            </xsd:schema>
          </wsdl:types>

          <wsdl:message name="dummyRequest">
            <wsdl:part name="response" element="tns:input"/>
          </wsdl:message>
          <wsdl:message name="dummyResponse">
            <wsdl:part name="response" element="tns:input2"/>
          </wsdl:message>

          <wsdl:portType name="TestPortType">
            <wsdl:operation name="TestOperation1">
              <wsdl:input message="dummyRequest" wsaw:Action="urn:dummyRequest"/>
              <wsdl:output message="dummyResponse"  wsaw:Action="urn:dummyResponse"/>
            </wsdl:operation>
          </wsdl:portType>

          <wsdl:binding name="TestBinding" type="tns:TestPortType">
            <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
            <wsdl:operation name="TestOperation1">
              <soap:operation soapAction=""/>
              <wsdl:input>
                <soap:body use="literal"/>
              </wsdl:input>
              <wsdl:output>
                <soap:body use="literal"/>
              </wsdl:output>
            </wsdl:operation>
          </wsdl:binding>
          <wsdl:service name="TestService">
            <wsdl:documentation>Test service</wsdl:documentation>
            <wsdl:port name="TestPortType" binding="tns:TestBinding">
              <soap:address location="http://tests.python-zeep.org/test"/>
            </wsdl:port>
          </wsdl:service>
        </wsdl:definitions>
    """.strip())

    client = stub(plugins=[], wsse=None)

    transport = DummyTransport()
    client = Client(wsdl_main, transport=transport)
    binding = client.wsdl.services.get('TestService').ports.get(
        'TestPortType').binding

    envelope, headers = binding._create(
        'TestOperation1',
        args=['foo'],
        kwargs={},
        client=client,
        options={'address': 'http://tests.python-zeep.org/test'})
    expected = """
        <soap-env:Envelope
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
          <soap-env:Header  xmlns:wsa="http://www.w3.org/2005/08/addressing">
            <wsa:Action>urn:dummyRequest</wsa:Action>
            <wsa:MessageID>urn:uuid:ada686f9-5995-4088-bea4-239f694b2eaf</wsa:MessageID>
            <wsa:To>http://tests.python-zeep.org/test</wsa:To>
          </soap-env:Header>
          <soap-env:Body>
            <ns0:input xmlns:ns0="http://tests.python-zeep.org/xsd-main">foo</ns0:input>
          </soap-env:Body>
        </soap-env:Envelope>
    """
    assert_nodes_equal(expected, envelope)
Exemplo n.º 37
0
def options(session):
    return stub(isolated_mode=False,
                index_url='default_url',
                skip_requirements_regex=False,
                format_control=FormatControl(set(), set()))
Exemplo n.º 38
0
    def test_version_search(self, pyramid_request, metrics):
        class FakeQuery:
            def __init__(self, type, must):
                self.type = type
                self.must = must

            def __getitem__(self, name):
                self.offset = name.start
                self.limit = name.stop
                self.step = name.step
                return self

            def execute(self):
                assert self.type == "bool"
                assert [q.to_dict() for q in self.must] == [
                    {
                        "match": {
                            "name": {
                                "boost": 10,
                                "query": "foo"
                            }
                        }
                    },
                    {
                        "match": {
                            "version": {
                                "query": "1.0"
                            }
                        }
                    },
                ]
                assert self.offset is None
                assert self.limit == 100
                assert self.step is None
                return [
                    pretend.stub(
                        name="foo",
                        summary="my summary",
                        latest_version="1.0",
                        version=["1.0"],
                    ),
                    pretend.stub(
                        name="foo-bar",
                        summary="other summary",
                        latest_version="2.0",
                        version=["2.0", "1.0"],
                    ),
                ]

        pyramid_request.es = pretend.stub(query=FakeQuery)
        results = xmlrpc.search(pyramid_request, {
            "name": "foo",
            "version": "1.0"
        }, "and")
        assert results == [
            {
                "_pypi_ordering": False,
                "name": "foo",
                "summary": "my summary",
                "version": "1.0",
            },
            {
                "_pypi_ordering": False,
                "name": "foo-bar",
                "summary": "other summary",
                "version": "1.0",
            },
        ]
        assert metrics.histogram.calls == [
            pretend.call("warehouse.xmlrpc.search.results", 2)
        ]
Exemplo n.º 39
0
    def test_send_password_reset_email(self, pyramid_request, pyramid_config,
                                       token_service, monkeypatch):

        stub_user = pretend.stub(
            id='id',
            email='email',
            username='******',
            last_login='******',
            password_date='password_date',
        )
        pyramid_request.method = 'POST'
        token_service.dumps = pretend.call_recorder(lambda a: 'TOKEN')
        pyramid_request.find_service = pretend.call_recorder(
            lambda *a, **kw: token_service)

        subject_renderer = pyramid_config.testing_add_renderer(
            'email/password-reset.subject.txt')
        subject_renderer.string_response = 'Email Subject'
        body_renderer = pyramid_config.testing_add_renderer(
            'email/password-reset.body.txt')
        body_renderer.string_response = 'Email Body'

        send_email = pretend.stub(
            delay=pretend.call_recorder(lambda *args, **kwargs: None))
        pyramid_request.task = pretend.call_recorder(
            lambda *args, **kwargs: send_email)
        monkeypatch.setattr(email, 'send_email', send_email)

        result = email.send_password_reset_email(
            pyramid_request,
            user=stub_user,
        )

        assert result == {
            'token': 'TOKEN',
            'username': stub_user.username,
            'n_hours': token_service.max_age // 60 // 60,
        }
        subject_renderer.assert_()
        body_renderer.assert_(token='TOKEN', username=stub_user.username)
        assert token_service.dumps.calls == [
            pretend.call({
                'action': 'password-reset',
                'user.id': str(stub_user.id),
                'user.last_login': str(stub_user.last_login),
                'user.password_date': str(stub_user.password_date),
            }),
        ]
        assert pyramid_request.find_service.calls == [
            pretend.call(ITokenService, name='password'),
        ]
        assert pyramid_request.task.calls == [
            pretend.call(send_email),
        ]
        assert send_email.delay.calls == [
            pretend.call(
                'Email Body',
                'Email Subject',
                recipients=[stub_user.email],
            ),
        ]
Exemplo n.º 40
0
 def test_skip_regex_pattern_not_match(self):
     options = stub(skip_requirements_regex='.*Bad.*')
     line = '--extra-index-url Good'
     assert [(0, line)] == list(skip_regex(enumerate([line]), options))
Exemplo n.º 41
0
def test_analyze_disclosure(monkeypatch):

    metrics = collections.Counter()

    def metrics_increment(key):
        metrics.update([key])

    user_id = uuid.UUID(bytes=b"0" * 16)
    user = pretend.stub(id=user_id)
    database_macaroon = pretend.stub(user=user,
                                     id=12,
                                     caveats={"permissions": "user"},
                                     description="foo")

    find = pretend.call_recorder(lambda *a, **kw: database_macaroon)
    delete = pretend.call_recorder(lambda *a, **kw: None)
    record_event = pretend.call_recorder(lambda *a, **kw: None)
    svc = {
        utils.IMetricsService:
        pretend.stub(increment=metrics_increment),
        utils.IMacaroonService:
        pretend.stub(find_from_raw=find, delete_macaroon=delete),
        utils.IUserService:
        pretend.stub(record_event=record_event),
    }

    request = pretend.stub(find_service=lambda iface, context: svc[iface])

    send_email = pretend.call_recorder(lambda *a, **kw: None)
    monkeypatch.setattr(utils, "send_token_compromised_email_leak", send_email)

    utils.analyze_disclosure(
        request=request,
        disclosure_record={
            "type": "pypi_api_token",
            "token": "pypi-1234",
            "url": "http://example.com",
        },
        origin="github",
    )
    assert metrics == {
        "warehouse.token_leak.github.recieved": 1,
        "warehouse.token_leak.github.processed": 1,
        "warehouse.token_leak.github.valid": 1,
    }
    assert send_email.calls == [
        pretend.call(request,
                     user,
                     public_url="http://example.com",
                     origin="github")
    ]
    assert find.calls == [pretend.call(raw_macaroon="pypi-1234")]
    assert delete.calls == [pretend.call(macaroon_id="12")]
    assert record_event.calls == [
        pretend.call(
            user_id,
            tag="account:api_token:removed_leak",
            ip_address="127.0.0.1",
            additional={
                "macaroon_id": "12",
                "public_url": "http://example.com",
                "permissions": "user",
                "description": "foo",
            },
        )
    ]
Exemplo n.º 42
0
    def test_default_search_operator_with_spaces_in_values(
            self, pyramid_request, metrics):
        class FakeQuery:
            def __init__(self, type, must):
                self.type = type
                self.must = must

            def __getitem__(self, name):
                self.offset = name.start
                self.limit = name.stop
                self.step = name.step
                return self

            def execute(self):
                assert self.type == "bool"
                assert [q.to_dict() for q in self.must] == [{
                    "bool": {
                        "should": [
                            {
                                "match": {
                                    "summary": {
                                        "boost": 5,
                                        "query": "fix code"
                                    }
                                }
                            },
                            {
                                "match": {
                                    "summary": {
                                        "boost": 5,
                                        "query": "like this"
                                    }
                                }
                            },
                        ]
                    }
                }]
                assert self.offset is None
                assert self.limit == 100
                assert self.step is None
                return [
                    pretend.stub(
                        name="foo",
                        summary="fix code",
                        latest_version="1.0",
                        version=["1.0"],
                    ),
                    pretend.stub(
                        name="foo-bar",
                        summary="like this",
                        latest_version="2.0",
                        version=["2.0", "1.0"],
                    ),
                ]

        pyramid_request.es = pretend.stub(query=FakeQuery)
        results = xmlrpc.search(pyramid_request,
                                {"summary": ["fix code", "like this"]})
        assert results == [
            {
                "_pypi_ordering": False,
                "name": "foo",
                "summary": "fix code",
                "version": "1.0",
            },
            {
                "_pypi_ordering": False,
                "name": "foo-bar",
                "summary": "like this",
                "version": "2.0",
            },
        ]
        assert metrics.histogram.calls == [
            pretend.call("warehouse.xmlrpc.search.results", 2)
        ]
Exemplo n.º 43
0
    def test_brows_invalid_id(self, request):
        request = pretend.stub(params={"c": '7"'})

        with pytest.raises(HTTPNotFound):
            pypi.browse(request)
Exemplo n.º 44
0
    def test_bails_if_vary(self, vary):
        request = pretend.stub()
        response = pretend.stub(vary=vary)

        compressor(request, response)
Exemplo n.º 45
0
def test_routes(warehouse):
    docs_route_url = pretend.stub()

    class FakeConfig:

        def __init__(self):
            self.registry = pretend.stub(settings={
                "docs.url": docs_route_url,
                "files.url": "https://files.example.com/packages/{path}",
            })
            if warehouse:
                self.registry.settings["warehouse.domain"] = warehouse

        def get_settings(self):
            return self.registry.settings

        @staticmethod
        @pretend.call_recorder
        def add_route(*args, **kwargs):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_template_view(*args, **kwargs):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_redirect(*args, **kwargs):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_pypi_action_route(name, action, **kwargs):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_pypi_action_redirect(action, target, **kwargs):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_xmlrpc_endpoint(endpoint, pattern, header, domain=None):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_policy(name, filename):
            pass

    config = FakeConfig()
    includeme(config)

    assert config.add_route.calls == [
        pretend.call("health", "/_health/"),
        pretend.call("force-status", "/_force-status/{status:[45]\d\d}/"),
        pretend.call('index', '/', domain=warehouse),
        pretend.call("robots.txt", "/robots.txt", domain=warehouse),
        pretend.call("opensearch.xml", "/opensearch.xml", domain=warehouse),
        pretend.call("index.sitemap.xml", "/sitemap.xml", domain=warehouse),
        pretend.call(
            "bucket.sitemap.xml",
            "/{bucket}.sitemap.xml",
            domain=warehouse,
        ),
        pretend.call(
            "includes.current-user-indicator",
            "/_includes/current-user-indicator/",
            domain=warehouse,
        ),
        pretend.call(
            "includes.flash-messages",
            "/_includes/flash-messages/",
            domain=warehouse,
        ),
        pretend.call(
            "includes.current-user-profile-callout",
            "/_includes/current-user-profile-callout/{username}",
            factory="warehouse.accounts.models:UserFactory",
            traverse="/{username}",
            domain=warehouse,
        ),
        pretend.call(
            "includes.edit-project-button",
            "/_includes/edit-project-button/{project_name}",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{project_name}",
            domain=warehouse,
        ),
        pretend.call(
            "includes.profile-actions",
            "/_includes/profile-actions/{username}",
            factory="warehouse.accounts.models:UserFactory",
            traverse="/{username}",
            domain=warehouse,
        ),
        pretend.call("classifiers", "/classifiers/", domain=warehouse),
        pretend.call("search", "/search/", domain=warehouse),
        pretend.call(
            "accounts.profile",
            "/user/{username}/",
            factory="warehouse.accounts.models:UserFactory",
            traverse="/{username}",
            domain=warehouse,
        ),
        pretend.call("accounts.login", "/account/login/", domain=warehouse),
        pretend.call("accounts.logout", "/account/logout/", domain=warehouse),
        pretend.call(
            "accounts.register",
            "/account/register/",
            domain=warehouse,
        ),
        pretend.call(
            "accounts.request-password-reset",
            "/account/request-password-reset/",
            domain=warehouse,
        ),
        pretend.call(
            "accounts.reset-password",
            "/account/reset-password/",
            domain=warehouse,
        ),
        pretend.call(
            "accounts.verify-email",
            "/account/verify-email/",
            domain=warehouse,
        ),
        pretend.call(
            "manage.account",
            "/manage/account/",
            domain=warehouse
        ),
        pretend.call(
            "manage.projects",
            "/manage/projects/",
            domain=warehouse
        ),
        pretend.call(
            "manage.project.settings",
            "/manage/project/{project_name}/settings/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{project_name}",
            domain=warehouse,
        ),
        pretend.call(
            "manage.project.delete_project",
            "/manage/project/{project_name}/delete_project/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{project_name}",
            domain=warehouse,
        ),
        pretend.call(
            "manage.project.destroy_docs",
            "/manage/project/{project_name}/delete_project_docs/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{project_name}",
            domain=warehouse,
        ),
        pretend.call(
            "manage.project.releases",
            "/manage/project/{project_name}/releases/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{project_name}",
            domain=warehouse,
        ),
        pretend.call(
            "manage.project.release",
            "/manage/project/{project_name}/release/{version}/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{project_name}/{version}",
            domain=warehouse,
        ),
        pretend.call(
            "manage.project.roles",
            "/manage/project/{project_name}/collaboration/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{project_name}",
            domain=warehouse,
        ),
        pretend.call(
            "manage.project.change_role",
            "/manage/project/{project_name}/collaboration/change/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{project_name}",
            domain=warehouse,
        ),
        pretend.call(
            "manage.project.delete_role",
            "/manage/project/{project_name}/collaboration/delete/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{project_name}",
            domain=warehouse,
        ),
        pretend.call(
            "manage.project.documentation",
            "/manage/project/{project_name}/documentation/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{project_name}",
            domain=warehouse,
        ),
        pretend.call(
            "manage.project.history",
            "/manage/project/{project_name}/history/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{project_name}",
            domain=warehouse,
        ),
        pretend.call(
            "packaging.project",
            "/project/{name}/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{name}",
            domain=warehouse,
        ),
        pretend.call(
            "packaging.release",
            "/project/{name}/{version}/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{name}/{version}",
            domain=warehouse,
        ),
        pretend.call(
            "packaging.file",
            "https://files.example.com/packages/{path}",
        ),
        pretend.call("ses.hook", "/_/ses-hook/", domain=warehouse),
        pretend.call("rss.updates", "/rss/updates.xml", domain=warehouse),
        pretend.call("rss.packages", "/rss/packages.xml", domain=warehouse),
        pretend.call("legacy.api.simple.index", "/simple/", domain=warehouse),
        pretend.call(
            "legacy.api.simple.detail",
            "/simple/{name}/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{name}/",
            read_only=True,
            domain=warehouse,
        ),
        pretend.call(
            "legacy.api.json.project",
            "/pypi/{name}/json",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{name}",
            read_only=True,
            domain=warehouse,
        ),
        pretend.call(
            "legacy.api.json.release",
            "/pypi/{name}/{version}/json",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{name}/{version}",
            read_only=True,
            domain=warehouse,
        ),
        pretend.call("legacy.docs", docs_route_url),
    ]

    assert config.add_template_view.calls == [
        pretend.call("help", "/help/", "pages/help.html"),
        pretend.call("security", "/security/", "pages/security.html"),
        pretend.call(
            "sponsors",
            "/sponsors/",
            "warehouse:templates/pages/sponsors.html",
        ),
    ]

    assert config.add_redirect.calls == [
        pretend.call("/p/{name}/", "/project/{name}/", domain=warehouse),
        pretend.call("/pypi/{name}/", "/project/{name}/", domain=warehouse),
        pretend.call(
            "/pypi/{name}/{version}/",
            "/project/{name}/{version}/",
            domain=warehouse,
        ),
        pretend.call("/pypi/", "/", domain=warehouse),
        pretend.call(
            "/packages/{path:.*}",
            "https://files.example.com/packages/{path}",
            domain=warehouse,
        ),
    ]

    assert config.add_pypi_action_route.calls == [
        pretend.call(
            "legacy.api.pypi.file_upload",
            "file_upload",
            domain=warehouse,
        ),
        pretend.call("legacy.api.pypi.submit", "submit", domain=warehouse),
        pretend.call(
            "legacy.api.pypi.submit_pkg_info",
            "submit_pkg_info",
            domain=warehouse,
        ),
        pretend.call(
            "legacy.api.pypi.doc_upload",
            "doc_upload",
            domain=warehouse,
        ),
        pretend.call("legacy.api.pypi.doap", "doap", domain=warehouse),
        pretend.call(
            "legacy.api.pypi.list_classifiers",
            "list_classifiers",
            domain=warehouse,
        ),
        pretend.call(
            'legacy.api.pypi.search',
            'search',
            domain=warehouse,
        ),
        pretend.call(
            'legacy.api.pypi.browse',
            'browse',
            domain=warehouse,
        ),
        pretend.call(
            'legacy.api.pypi.files',
            'files',
            domain=warehouse,
        ),
        pretend.call(
            'legacy.api.pypi.display',
            'display',
            domain=warehouse,
        ),
    ]

    assert config.add_pypi_action_redirect.calls == [
        pretend.call("rss", "/rss/updates.xml", domain=warehouse),
        pretend.call("packages_rss", "/rss/packages.xml", domain=warehouse),
    ]

    assert config.add_xmlrpc_endpoint.calls == [
        pretend.call(
            "pypi",
            pattern="/pypi",
            header="Content-Type:text/xml",
            domain=warehouse,
        ),
        pretend.call(
            "pypi_slash",
            pattern="/pypi/",
            header="Content-Type:text/xml",
            domain=warehouse,
        ),
        pretend.call(
            "RPC2",
            pattern="/RPC2",
            header="Content-Type:text/xml",
            domain=warehouse,
        ),
    ]

    assert config.add_policy.calls == [
        pretend.call("terms-of-use", "terms.md"),
    ]
Exemplo n.º 46
0
def test_forbidden_legacy():
    exc, request = pretend.stub(), pretend.stub()
    resp = pypi.forbidden_legacy(exc, request)
    assert resp is exc
Exemplo n.º 47
0
def test_extract_http_macaroon(auth, result):
    request = pretend.stub(headers=pretend.stub(
        get=pretend.call_recorder(lambda k: auth)))

    assert auth_policy._extract_http_macaroon(request) == result
Exemplo n.º 48
0
    def test_browse_no_id(self):
        request = pretend.stub(params={})

        with pytest.raises(HTTPNotFound):
            pypi.browse(request)
Exemplo n.º 49
0
 def test_remember(self):
     policy = auth_policy.MacaroonAuthenticationPolicy()
     assert policy.remember(pretend.stub(), pretend.stub()) == []
Exemplo n.º 50
0
 def setUp(self):
     self.addUser = call_recorder(
         lambda *args, **kwargs: defer.succeed("ignored")
     )
     store = stub(addUser=self.addUser)
     self.adminFactory = stub(store=store)
Exemplo n.º 51
0
def test_xmlrpc_browse_invalid_arg():
    interface = xmlrpc.Interface(pretend.stub(), pretend.stub())

    with pytest.raises(TypeError):
        interface.browse('hello')
Exemplo n.º 52
0
 def test_forget(self):
     policy = auth_policy.MacaroonAuthenticationPolicy()
     assert policy.forget(pretend.stub()) == []
Exemplo n.º 53
0
 def test_unsupported_evp_pkey_type(self):
     key = pretend.stub(type="unsupported")
     with raises_unsupported_algorithm(None):
         backend._evp_pkey_to_private_key(key)
     with raises_unsupported_algorithm(None):
         backend._evp_pkey_to_public_key(key)
Exemplo n.º 54
0
def test_xmlrpc_search_invalid():
    interface = xmlrpc.Interface(pretend.stub(), pretend.stub())

    with pytest.raises(TypeError):
        interface.search({}, "fake!")
Exemplo n.º 55
0
def test_extract_document():
    pmap = ProjectMapping(index=pretend.stub())
    document = pmap.extract_document({"name": "Test Name"})

    assert document == {"name": "Test Name", "name_keyword": "test name"}
Exemplo n.º 56
0
def test_all_release_urls(monkeypatch):
    dt = datetime.datetime.utcnow()

    urls = {
        '1.0': [
            dict(
                name="spam",
                url='/packages/source/t/spam/spam-1.0.tar.gz',
                version="1.0",
                filename="spam-1.0.tar.gz",
                python_version="source",
                packagetype="sdist",
                md5_digest="0cc175b9c0f1b6a831c399e269772661",
                downloads=10,
                size=1234,
                pgp_url=None,
                comment_text='download for great justice',
                upload_time=dt,
            ),
            dict(
                name="spam",
                url='/packages/source/t/spam/spam-1.0.zip',
                version="1.0",
                filename="spam-1.0.zip",
                python_version="source",
                packagetype="sdist",
                md5_digest="0cc175b3c0f1b6a831c399e269772661",
                downloads=12,
                size=1235,
                pgp_url=None,
                comment_text=None,
                upload_time=dt,
            )
        ],
        '2.0': [
            dict(
                name="spam",
                url='/packages/source/t/spam/spam-2.0.tar.gz',
                version="2.0",
                filename="spam-2.0.tar.gz",
                python_version="source",
                packagetype="sdist",
                md5_digest="0cc175b9c0f1b6a831c399e269772661",
                downloads=10,
                size=1234,
                pgp_url=None,
                comment_text='download for great justice',
                upload_time=dt,
            )
        ]
    }

    vers = ['1.0', '2.0']

    app = pretend.stub(db=pretend.stub(packaging=pretend.stub(
        get_downloads=pretend.call_recorder(lambda *a: urls[a[1]]),
        get_project_versions=pretend.call_recorder(lambda *a: vers),
    ), ), )

    interface = xmlrpc.Interface(app, pretend.stub())

    result = interface.all_release_urls('spam')

    assert app.db.packaging.get_downloads.calls == [
        pretend.call('spam', '1.0'),
        pretend.call('spam', '2.0'),
    ]
    assert result == {
        '1.0': [
            dict(
                url='/packages/source/t/spam/spam-1.0.tar.gz',
                packagetype="sdist",
                filename="spam-1.0.tar.gz",
                size=1234,
                md5_digest="0cc175b9c0f1b6a831c399e269772661",
                downloads=10,
                has_sig=False,
                python_version="source",
                comment_text='download for great justice',
                upload_time=dt,
            ),
            dict(
                url='/packages/source/t/spam/spam-1.0.zip',
                packagetype="sdist",
                filename="spam-1.0.zip",
                size=1235,
                md5_digest="0cc175b3c0f1b6a831c399e269772661",
                downloads=12,
                has_sig=False,
                python_version="source",
                comment_text=None,
                upload_time=dt,
            )
        ],
        '2.0': [
            dict(
                url='/packages/source/t/spam/spam-2.0.tar.gz',
                packagetype="sdist",
                filename="spam-2.0.tar.gz",
                size=1234,
                md5_digest="0cc175b9c0f1b6a831c399e269772661",
                downloads=10,
                has_sig=False,
                python_version="source",
                comment_text='download for great justice',
                upload_time=dt,
            )
        ]
    }
Exemplo n.º 57
0
 def test_configure_all(self, proxy):
     x = stub()
     configure(processors=[x], context_class=dict)
     b = proxy.bind()
     assert [x] == b._processors
     assert dict is b._context.__class__
Exemplo n.º 58
0
def test_routes(warehouse):
    docs_route_url = pretend.stub()

    class FakeConfig:
        def __init__(self):
            self.registry = pretend.stub(
                settings={
                    "docs.url": docs_route_url,
                    "files.url": "https://files.example.com/packages/{path}",
                })
            if warehouse:
                self.registry.settings["warehouse.domain"] = warehouse

        def get_settings(self):
            return self.registry.settings

        @staticmethod
        @pretend.call_recorder
        def add_route(*args, **kwargs):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_template_view(*args, **kwargs):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_redirect(*args, **kwargs):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_pypi_action_route(name, action, **kwargs):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_pypi_action_redirect(action, target, **kwargs):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_xmlrpc_endpoint(endpoint, pattern, header, domain=None):
            pass

        @staticmethod
        @pretend.call_recorder
        def add_policy(name, filename):
            pass

    config = FakeConfig()
    includeme(config)

    assert config.add_route.calls == [
        pretend.call("health", "/_health/"),
        pretend.call('index', '/', domain=warehouse),
        pretend.call("robots.txt", "/robots.txt", domain=warehouse),
        pretend.call("opensearch.xml", "/opensearch.xml", domain=warehouse),
        pretend.call("index.sitemap.xml", "/sitemap.xml", domain=warehouse),
        pretend.call(
            "bucket.sitemap.xml",
            "/{bucket}.sitemap.xml",
            domain=warehouse,
        ),
        pretend.call(
            "includes.current-user-indicator",
            "/_includes/current-user-indicator/",
            domain=warehouse,
        ),
        pretend.call("search", "/search/", domain=warehouse),
        pretend.call(
            "accounts.profile",
            "/user/{username}/",
            factory="warehouse.accounts.models:UserFactory",
            traverse="/{username}",
            domain=warehouse,
        ),
        pretend.call("accounts.login", "/account/login/", domain=warehouse),
        pretend.call("accounts.logout", "/account/logout/", domain=warehouse),
        pretend.call(
            "accounts.register",
            "/account/register/",
            domain=warehouse,
        ),
        pretend.call(
            "packaging.project",
            "/project/{name}/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{name}",
            domain=warehouse,
        ),
        pretend.call(
            "packaging.release",
            "/project/{name}/{version}/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{name}/{version}",
            domain=warehouse,
        ),
        pretend.call(
            "packaging.file",
            "https://files.example.com/packages/{path}",
        ),
        pretend.call("rss.updates", "/rss/updates.xml", domain=warehouse),
        pretend.call("rss.packages", "/rss/packages.xml", domain=warehouse),
        pretend.call("legacy.api.simple.index", "/simple/", domain=warehouse),
        pretend.call(
            "legacy.api.simple.detail",
            "/simple/{name}/",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{name}/",
            read_only=True,
            domain=warehouse,
        ),
        pretend.call(
            "legacy.api.json.project",
            "/pypi/{name}/json",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{name}",
            read_only=True,
            domain=warehouse,
        ),
        pretend.call(
            "legacy.api.json.release",
            "/pypi/{name}/{version}/json",
            factory="warehouse.packaging.models:ProjectFactory",
            traverse="/{name}/{version}",
            read_only=True,
            domain=warehouse,
        ),
        pretend.call("legacy.docs", docs_route_url),
    ]

    assert config.add_template_view.calls == [
        pretend.call("help", "/help/", "pages/help.html"),
        pretend.call("security", "/security/", "pages/security.html"),
        pretend.call(
            "sponsors",
            "/sponsors/",
            "warehouse:templates/pages/sponsors.html",
        ),
    ]

    assert config.add_redirect.calls == [
        pretend.call("/pypi/{name}/", "/project/{name}/", domain=warehouse),
        pretend.call(
            "/pypi/{name}/{version}/",
            "/project/{name}/{version}/",
            domain=warehouse,
        ),
        pretend.call(
            "/packages/{path:.*}",
            "https://files.example.com/packages/{path}",
            domain=warehouse,
        ),
    ]

    assert config.add_pypi_action_route.calls == [
        pretend.call(
            "legacy.api.pypi.file_upload",
            "file_upload",
            domain=warehouse,
        ),
        pretend.call("legacy.api.pypi.submit", "submit", domain=warehouse),
        pretend.call(
            "legacy.api.pypi.submit_pkg_info",
            "submit_pkg_info",
            domain=warehouse,
        ),
        pretend.call(
            "legacy.api.pypi.doc_upload",
            "doc_upload",
            domain=warehouse,
        ),
        pretend.call("legacy.api.pypi.doap", "doap", domain=warehouse),
        pretend.call(
            "legacy.api.pypi.list_classifiers",
            "list_classifiers",
            domain=warehouse,
        ),
    ]

    assert config.add_pypi_action_redirect.calls == [
        pretend.call("rss", "/rss/updates.xml", domain=warehouse),
        pretend.call("packages_rss", "/rss/packages.xml", domain=warehouse),
    ]

    assert config.add_xmlrpc_endpoint.calls == [
        pretend.call(
            "pypi",
            pattern="/pypi",
            header="Content-Type:text/xml",
            domain=warehouse,
        ),
    ]

    assert config.add_policy.calls == [
        pretend.call("terms-of-use", "terms.md"),
    ]
Exemplo n.º 59
0
 def test_create_service(self):
     request = pretend.stub(registry=pretend.stub(
         settings={"docs.path": "/the/one/two/"}))
     storage = LocalDocsStorage.create_service(None, request)
     assert storage.base == "/the/one/two/"
Exemplo n.º 60
0
def test_extract_id():
    pmap = ProjectMapping(index=pretend.stub())
    assert pmap.extract_id({"name": "test name"}) == "test name"