Example #1
0
    def update_me(self,
                  name: Optional[str] = None,
                  email: Optional[str] = None):
        """
        Update private profile information when authenticated through
        basic auth or OAuth with the user scope.

        If your email is set to private and you send an email parameter as part of this
        request to update your profile, your privacy settings are still enforced:
        the email address will not be displayed on your public profile or via the API.

        Args:
            name: The new name of the user.
            email: The publicly visible email address of the user.

        Returns:
            Public and private profile information for currently authenticated user.
        """
        assert self.auth is not None, "`auth` must be set for this method"
        data = {k: v for k, v in vars().items() if v is not None}
        assert data, "At least one field to update must be provided"
        request = Request(Method.PATCH,
                          self.url("/user"),
                          json=data,
                          auth=self.auth)
        return fetch(self.driver, request, model=Me)
Example #2
0
def test_base_middleware() -> None:
    def handler(request: Request, *args, **kwargs) -> Response:
        return factories.make_response(b"Hello, World!")

    request = Request(Method.GET, "https://example.com")
    response = BaseMiddleware(handler)(request)
    assert response.content == b"Hello, World!"
Example #3
0
def test_base_middleware_handler_raises_exception() -> None:
    def handler(request: Request, *args, **kwargs) -> Response:
        raise Exception("You shall not pass")

    request = Request(Method.GET, "https://example.com")
    with pytest.raises(Exception):
        BaseMiddleware(handler)(request)
Example #4
0
 def basic_auth(self, login, password):
     """Prompts the user for authorization using HTTP Basic Auth."""
     url = self.url("/basic-auth/{user}/{passwd}",
                    user=login,
                    passwd=password)
     request = Request(Method.GET, url, auth=(login, password))
     return self.driver.fetch(request)
Example #5
0
def test_driver_protocol() -> None:
    response = factories.make_response(b'"Hello, World!"')
    driver = factories.make_driver(response)
    request = Request(Method.GET, "https://example.com")
    response = driver.fetch(request)
    assert response.status_code == 200
    assert response.text() == '"Hello, World!"'
    assert response.json() == "Hello, World!"
Example #6
0
async def test_base_middleware_handler_raises_exception_async() -> None:
    async def handler(request: Request, *args, **kwargs) -> Response:
        raise Exception("You shall not pass")

    request = Request(Method.GET, "https://example.com")
    with pytest.raises(Exception):
        # see https://github.com/python/mypy/issues/8283
        await cast(Awaitable[Response], BaseMiddleware(handler)(request))
Example #7
0
 def post(self, data=None, files=None, json=None):
     """The request's POST parameters."""
     request = Request(Method.POST,
                       self.url("/post"),
                       data=data,
                       files=files,
                       json=json)
     return self.driver.fetch(request)
Example #8
0
async def test_base_middleware_async() -> None:
    async def handler(request: Request, *args, **kwargs) -> Response:
        return factories.make_response(b"Hello, World!")

    request = Request(Method.GET, "https://example.com")
    # see https://github.com/python/mypy/issues/8283
    response = await cast(Awaitable[Response],
                          BaseMiddleware(handler)(request))
    assert response.content == b"Hello, World!"
Example #9
0
    def complex_auth_flow(self, token: str):
        """Echoes passed token and uses it for bearer authentication."""
        def auth_flow():
            response = yield Request(Method.POST,
                                     self.url("/anything"),
                                     data=token)
            return TokenAuth(response.json()["data"])()

        request = Request(Method.GET, self.url("/bearer"), auth=auth_flow)
        return self.driver.fetch(request)
Example #10
0
    def me(self):
        """
        Lists public and private profile information when authenticated through
        basic auth or OAuth with the user scope.

        Returns:
            Public and private profile information for currently authenticated user.
        """
        assert self.auth is not None, "`auth` must be set for this method"
        request = Request(Method.GET, self.url("/user"), auth=self.auth)
        return fetch(self.driver, request, model=Me)
Example #11
0
def test_request_mutually_exclusive_parameters(data, files, json):
    with pytest.raises(ValueError) as excinfo:
        Request(
            Method.GET,
            "https://example.com",
            data=data,
            files=files,
            json=json,
        )
    expected = "`data`, `files` and `json` parameters are mutually exclusive"
    assert str(excinfo.value) == expected
Example #12
0
def make_response(content: bytes, **kwargs) -> Response:
    defaults: Dict[str, Any] = {
        "request": Request(Method.GET, "https://example.com"),
        "status_code": 200,
        "url": "https://example.com/",
        "headers": CaseInsensitiveDict(),
        "cookies": SimpleCookie(),
        "encoding": "utf-8",
        "content": content,
    }
    defaults.update(kwargs)
    return Response(**defaults)
Example #13
0
    def user(self, username: str):
        """
        Provides publicly available information about someone with a GitHub account.

        Args:
            username: User's username on the GitHub

        Returns:
            Public profile information for GitHub User.
        """
        request = Request(Method.GET,
                          self.url("/users/{username}", username=username))
        return fetch(self.driver, request, model=UserDetail)
Example #14
0
    def users(self, since: int = 0):
        """
        Lists all users, in the order that they signed up on GitHub.

        Pagination is powered exclusively by the since parameter.

        Args:
            since: The integer ID of the last User that you've seen.

        Returns:
            List of GitHub users
        """
        params = {"since": str(since)}
        request = Request(Method.GET, self.url("/users"), query_params=params)
        return fetch(self.driver, request, model=List[User])
Example #15
0
 def process_request(self, request: Request) -> Request:
     request.headers = {"Request": "middleware"}
     return super().process_request(request)
Example #16
0
def test_request_string_representation() -> None:
    request = Request(Method.GET, "https://example.com")
    assert str(request) == "<Request [GET]>"
Example #17
0
 def cookies(self, cookies):
     """Returns cookie data."""
     request = Request(Method.GET, self.url("/cookies"), cookies=cookies)
     return self.driver.fetch(request)
Example #18
0
 def headers(self, headers):
     """Return the incoming request's HTTP headers."""
     request = Request(Method.GET, self.url("/headers"), headers=headers)
     return self.driver.fetch(request)
Example #19
0
async def test_fetch_returns_model_from_source_async() -> None:
    request = Request(Method.GET, "https://example.com")
    driver_response = factories.make_response(b'{"user": {"id": 1}}')
    driver = factories.make_async_driver(driver_response)
    user = await fetch(driver, request, model=User, source="user")
    assert user == User(id=1)
Example #20
0
 def bearer_auth(self, token):
     """Prompts the user for authorization using bearer authentication."""
     request = Request(Method.GET,
                       self.url("/bearer"),
                       auth=TokenAuth(token))
     return self.driver.fetch(request)
Example #21
0
def test_fetch_returns_model() -> None:
    request = Request(Method.GET, "https://example.com")
    driver_response = factories.make_response(b'{"id": 1}')
    driver = factories.make_driver(driver_response)
    user = fetch(driver, request, model=User)
    assert user == User(id=1)
Example #22
0
 def html(self):
     """Returns a simple HTML document."""
     request = Request(Method.GET, self.url("/html"))
     return self.driver.fetch(request)
Example #23
0
 def delay(self, delay, timeout):
     """Returns a delayed response (max of 10 seconds)."""
     request = Request(Method.GET, self.url("/delay/{delay}", delay=delay))
     return self.driver.fetch(request, timeout=timeout)
Example #24
0
 def set_cookie(self, name, value):
     """Sets a cookie and redirects to cookie list."""
     url = self.url("/cookies/set/{name}/{value}", name=name, value=value)
     request = Request(Method.GET, url)
     return self.driver.fetch(request)
Example #25
0
 def get(self, params=None):
     """The request's query parameters."""
     request = Request(Method.GET, self.url("/get"), query_params=params)
     return self.driver.fetch(request)
Example #26
0
 def auth_flow():
     response = yield Request(Method.POST,
                              self.url("/anything"),
                              data=token)
     return TokenAuth(response.json()["data"])()
Example #27
0
 def response_headers(self, headers):
     """Returns a set of response headers from the query string."""
     request = Request(Method.GET,
                       self.url("/response-headers"),
                       query_params=headers)
     return self.driver.fetch(request)
Example #28
0
async def test_fetch_returns_response_async() -> None:
    request = Request(Method.GET, "https://example.com")
    driver_response = factories.make_response(b"Hello, World")
    driver = factories.make_async_driver(driver_response)
    response = await fetch(driver, request)
    assert response.content == b"Hello, World"
Example #29
0
 def user_request(self, user_id: int) -> Request:
     return Request(Method.GET, self.url("/users/{user_id}",
                                         user_id=user_id))