Exemple #1
0
 def test_initialize(self):
     requestor = prawcore.Requestor("prawcore:test (by /u/bboe)")
     self.assertEqual(
         "prawcore:test (by /u/bboe) prawcore/{}".format(
             prawcore.__version__),
         requestor._http.headers["User-Agent"],
     )
Exemple #2
0
    def test_request__chunked_encoding_retry(self, mock_session):
        session_instance = mock_session.return_value

        # Handle Auth
        response_dict = {"access_token": "", "expires_in": 99, "scope": ""}
        session_instance.request.return_value = Mock(
            headers={}, json=lambda: response_dict, status_code=200
        )
        requestor = prawcore.Requestor("prawcore:test (by /u/bboe)")
        authorizer = readonly_authorizer(requestor=requestor)
        session_instance.request.reset_mock()

        # Fail on subsequent request
        exception = ChunkedEncodingError()
        session_instance.request.side_effect = exception

        expected = (
            "prawcore",
            "WARNING",
            "Retrying due to ChunkedEncodingError() status: GET "
            "https://oauth.reddit.com/",
        )

        with LogCapture(level=logging.WARNING) as log_capture:
            with self.assertRaises(RequestException) as context_manager:
                prawcore.Session(authorizer).request("GET", "/")
            log_capture.check(expected, expected)
        self.assertIsInstance(context_manager.exception, RequestException)
        self.assertIs(exception, context_manager.exception.original_exception)
        self.assertEqual(3, session_instance.request.call_count)
Exemple #3
0
    def test_request__read_timeout_retry(self, mock_session):
        session_instance = mock_session.return_value

        # Handle Auth
        response_dict = {'access_token': '', 'expires_in': 99, 'scope': ''}
        session_instance.request.return_value = Mock(
            headers={}, json=lambda: response_dict, status_code=200)
        requestor = prawcore.Requestor('prawcore:test (by /u/bboe)')
        authorizer = readonly_authorizer(requestor=requestor)
        session_instance.request.reset_mock()

        # Fail on subsequent request
        exception = ReadTimeout()
        session_instance.request.side_effect = exception

        expected = ('prawcore', 'WARNING',
                    'Retrying due to ReadTimeout() status: GET '
                    'https://oauth.reddit.com/')

        with LogCapture(level=logging.WARNING) as log_capture:
            with self.assertRaises(RequestException) as context_manager:
                prawcore.Session(authorizer).request('GET', '/')
            log_capture.check(expected, expected)
        self.assertIsInstance(context_manager.exception, RequestException)
        self.assertIs(exception, context_manager.exception.original_exception)
        self.assertEqual(3, session_instance.request.call_count)
Exemple #4
0
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) != 2:
        print("Usage: {} USERNAME".format(sys.argv[0]))
        return 1

    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor("prawcore_read_only_example"),
        os.environ["PRAWCORE_CLIENT_ID"],
        os.environ["PRAWCORE_CLIENT_SECRET"],
    )
    authorizer = prawcore.ReadOnlyAuthorizer(authenticator)
    authorizer.refresh()

    user = sys.argv[1]
    with prawcore.session(authorizer) as session:
        data = session.request("GET", "/api/v1/user/{}/trophies".format(user))

    for trophy in data["data"]["trophies"]:
        description = trophy["data"]["description"]
        print(
            trophy["data"]["name"]
            + (" ({})".format(description) if description else "")
        )

    return 0
Exemple #5
0
 def test_request__wrap_request_exceptions(self, mock_session):
     exception = Exception("prawcore wrap_request_exceptions")
     session_instance = mock_session.return_value
     session_instance.request.side_effect = exception
     requestor = prawcore.Requestor("prawcore:test (by /u/bboe)")
     with self.assertRaises(prawcore.RequestException) as context_manager:
         requestor.request("get", "http://a.b", data="bar")
     self.assertIsInstance(context_manager.exception, RequestException)
     self.assertIs(exception, context_manager.exception.original_exception)
     self.assertEqual(("get", "http://a.b"),
                      context_manager.exception.request_args)
     self.assertEqual({"data": "bar"},
                      context_manager.exception.request_kwargs)
 def test_request__wrap_request_exceptions(self, mock_session):
     exception = Exception('prawcore wrap_request_exceptions')
     session_instance = mock_session.return_value
     session_instance.request.side_effect = exception
     requestor = prawcore.Requestor('prawcore:test (by /u/bboe)')
     with self.assertRaises(prawcore.RequestException) as context_manager:
         requestor.request('get', 'http://a.b', data='bar')
     self.assertIsInstance(context_manager.exception, RequestException)
     self.assertIs(exception, context_manager.exception.original_exception)
     self.assertEqual(('get', 'http://a.b'),
                      context_manager.exception.request_args)
     self.assertEqual({'data': 'bar'},
                      context_manager.exception.request_kwargs)
    def test_request__use_custom_session(self):
        override = 'REQUEST OVERRIDDEN'
        custom_header = 'CUSTOM SESSION HEADER'
        headers = {'session_header': custom_header}
        attrs = {'request.return_value': override, 'headers': headers}
        session = Mock(**attrs)

        requestor = prawcore.Requestor('prawcore:test (by /u/bboe)',
                                       session=session)

        self.assertEqual(
            'prawcore:test (by /u/bboe) prawcore/{}'.format(
                prawcore.__version__), requestor._http.headers['User-Agent'])
        self.assertEqual(requestor._http.headers['session_header'],
                         custom_header)

        self.assertEqual(requestor.request('https://reddit.com'), override)
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} USERNAME")
        return 1

    caching_requestor = prawcore.Requestor(
        "prawcore_device_id_auth_example", session=CachingSession()
    )
    authenticator = prawcore.TrustedAuthenticator(
        caching_requestor,
        os.environ["PRAWCORE_CLIENT_ID"],
        os.environ["PRAWCORE_CLIENT_SECRET"],
    )
    authorizer = prawcore.ReadOnlyAuthorizer(authenticator)
    authorizer.refresh()

    user = sys.argv[1]
    with prawcore.session(authorizer) as session:
        data1 = session.request("GET", f"/api/v1/user/{user}/trophies")

    with prawcore.session(authorizer) as session:
        data2 = session.request("GET", f"/api/v1/user/{user}/trophies")

    for trophy in data1["data"]["trophies"]:
        description = trophy["data"]["description"]
        print(
            "Original:",
            trophy["data"]["name"]
            + (f" ({description})" if description else ""),
        )

    for trophy in data2["data"]["trophies"]:
        description = trophy["data"]["description"]
        print(
            "Cached:",
            trophy["data"]["name"]
            + (f" ({description})" if description else ""),
        )
    print(
        "----\nCached == Original:",
        data2["data"]["trophies"] == data2["data"]["trophies"],
    )

    return 0
Exemple #9
0
def main():
    """Provide the program's entry point when directly executed."""
    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor('prawcore_script_auth_example'),
        os.environ['PRAWCORE_CLIENT_ID'],
        os.environ['PRAWCORE_CLIENT_SECRET'])
    authorizer = prawcore.ScriptAuthorizer(authenticator,
                                           os.environ['PRAWCORE_USERNAME'],
                                           os.environ['PRAWCORE_PASSWORD'])
    authorizer.refresh()

    with prawcore.session(authorizer) as session:
        data = session.request('GET', '/api/v1/me/friends')

    for friend in data['data']['children']:
        print(friend['name'])

    return 0
Exemple #10
0
    def test_request__use_custom_session(self):
        override = "REQUEST OVERRIDDEN"
        custom_header = "CUSTOM SESSION HEADER"
        headers = {"session_header": custom_header}
        attrs = {"request.return_value": override, "headers": headers}
        session = Mock(**attrs)

        requestor = prawcore.Requestor("prawcore:test (by /u/bboe)",
                                       session=session)

        self.assertEqual(
            f"prawcore:test (by /u/bboe) prawcore/{prawcore.__version__}",
            requestor._http.headers["User-Agent"],
        )
        self.assertEqual(requestor._http.headers["session_header"],
                         custom_header)

        self.assertEqual(requestor.request("https://reddit.com"), override)
Exemple #11
0
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) < 2:
        print("Usage: {} SCOPE...".format(sys.argv[0]))
        return 1

    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor("prawcore_refresh_token_example"),
        os.environ["PRAWCORE_CLIENT_ID"],
        os.environ["PRAWCORE_CLIENT_SECRET"],
        os.environ["PRAWCORE_REDIRECT_URI"],
    )

    state = str(random.randint(0, 65000))
    url = authenticator.authorize_url("permanent", sys.argv[1:], state)
    print(url)

    client = receive_connection()
    data = client.recv(1024).decode("utf-8")
    param_tokens = data.split(" ", 2)[1].split("?", 1)[1].split("&")
    params = {
        key: value
        for (key, value) in [token.split("=") for token in param_tokens]
    }

    if state != params["state"]:
        send_message(
            client,
            "State mismatch. Expected: {} Received: {}".format(
                state, params["state"]
            ),
        )
        return 1
    elif "error" in params:
        send_message(client, params["error"])
        return 1

    authorizer = prawcore.Authorizer(authenticator)
    authorizer.authorize(params["code"])

    send_message(client, "Refresh token: {}".format(authorizer.refresh_token))
    return 0
def main():
    """Provide the program's entry point when directly executed."""
    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor("prawcore_script_auth_example"),
        os.environ["PRAWCORE_CLIENT_ID"],
        os.environ["PRAWCORE_CLIENT_SECRET"],
    )
    authorizer = prawcore.ScriptAuthorizer(
        authenticator,
        os.environ["PRAWCORE_USERNAME"],
        os.environ["PRAWCORE_PASSWORD"],
    )
    authorizer.refresh()

    with prawcore.session(authorizer) as session:
        data = session.request("GET", "/api/v1/me/friends")

    for friend in data["data"]["children"]:
        print(friend["name"])

    return 0
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) != 2:
        print('Usage: {} USERNAME'.format(sys.argv[0]))
        return 1

    authenticator = prawcore.UntrustedAuthenticator(
        prawcore.Requestor('prawcore_device_id_auth_example'),
        os.environ['PRAWCORE_CLIENT_ID'])
    authorizer = prawcore.DeviceIDAuthorizer(authenticator)
    authorizer.refresh()

    user = sys.argv[1]
    with prawcore.session(authorizer) as session:
        data = session.request('GET', '/api/v1/user/{}/trophies'.format(user))

    for trophy in data['data']['trophies']:
        description = trophy['data']['description']
        print(trophy['data']['name'] +
              (' ({})'.format(description) if description else ''))

    return 0
Exemple #14
0
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} USERNAME")
        return 1

    authenticator = prawcore.UntrustedAuthenticator(
        prawcore.Requestor("prawcore_device_id_auth_example"),
        os.environ["PRAWCORE_CLIENT_ID"],
    )
    authorizer = prawcore.DeviceIDAuthorizer(authenticator)
    authorizer.refresh()

    user = sys.argv[1]
    with prawcore.session(authorizer) as session:
        data = session.request("GET", f"/api/v1/user/{user}/trophies")

    for trophy in data["data"]["trophies"]:
        description = trophy["data"]["description"]
        print(trophy["data"]["name"] +
              (f" ({description})" if description else ""))

    return 0
Exemple #15
0
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) < 2:
        print('Usage: {} SCOPE...'.format(sys.argv[0]))
        return 1

    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor('prawcore_refresh_token_example'),
        os.environ['PRAWCORE_CLIENT_ID'], os.environ['PRAWCORE_CLIENT_SECRET'],
        os.environ['PRAWCORE_REDIRECT_URI'])

    state = str(random.randint(0, 65000))
    url = authenticator.authorize_url('permanent', sys.argv[1:], state)
    print(url)

    client = receive_connection()
    data = client.recv(1024).decode('utf-8')
    param_tokens = data.split(' ', 2)[1].split('?', 1)[1].split('&')
    params = {
        key: value
        for (key, value) in [token.split('=') for token in param_tokens]
    }

    if state != params['state']:
        send_message(
            client, 'State mismatch. Expected: {} Received: {}'.format(
                state, params['state']))
        return 1
    elif 'error' in params:
        send_message(client, params['error'])
        return 1

    authorizer = prawcore.Authorizer(authenticator)
    authorizer.authorize(params['code'])

    send_message(client, 'Refresh token: {}'.format(authorizer.refresh_token))
    return 0
Exemple #16
0
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) != 2:
        print('Usage: {} USERNAME'.format(sys.argv[0]))
        return 1

    caching_requestor = prawcore.Requestor('prawcore_device_id_auth_example',
                                           session=CachingSession())
    authenticator = prawcore.TrustedAuthenticator(
        caching_requestor, os.environ['PRAWCORE_CLIENT_ID'],
        os.environ['PRAWCORE_CLIENT_SECRET'])
    authorizer = prawcore.ReadOnlyAuthorizer(authenticator)
    authorizer.refresh()

    user = sys.argv[1]
    with prawcore.session(authorizer) as session:
        data1 = session.request('GET', '/api/v1/user/{}/trophies'.format(user))

    with prawcore.session(authorizer) as session:
        data2 = session.request('GET', '/api/v1/user/{}/trophies'.format(user))

    for trophy in data1['data']['trophies']:
        description = trophy['data']['description']
        print(
            'Original:', trophy['data']['name'] +
            (' ({})'.format(description) if description else ''))

    for trophy in data2['data']['trophies']:
        description = trophy['data']['description']
        print(
            'Cached:', trophy['data']['name'] +
            (' ({})'.format(description) if description else ''))
    print('----\nCached == Original:',
          data2['data']['trophies'] == data2['data']['trophies'])

    return 0
Exemple #17
0
 def test_pickle(self):
     requestor = prawcore.Requestor("prawcore:test (by /u/bboe)")
     for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
         pickle.loads(pickle.dumps(requestor, protocol=protocol))
 def test_initialize(self):
     requestor = prawcore.Requestor('prawcore:test (by /u/bboe)')
     self.assertEqual(
         'prawcore:test (by /u/bboe) prawcore/{}'.format(
             prawcore.__version__), requestor._http.headers['User-Agent'])