Debian Codegraph @

test/test_oauth.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 # Copyright 2018-2023 Mike Fährmann
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License version 2 as
8 # published by the Free Software Foundation.
9
10 import os
11 import sys
12 import unittest
13 from unittest.mock import patch
14
15 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
16 from gallery_dl import oauth, text # noqa E402
17
18 TESTSERVER = "http://term.ie/oauth/example"
19 CONSUMER_KEY = "key"
20 CONSUMER_SECRET = "secret"
21 REQUEST_TOKEN = "requestkey"
22 REQUEST_TOKEN_SECRET = "requestsecret"
23 ACCESS_TOKEN = "accesskey"
24 ACCESS_TOKEN_SECRET = "accesssecret"
25
26
27 class TestOAuthSession(unittest.TestCase):
28
29 def test_concat(self):
30 concat = oauth.concat
31
32 self.assertEqual(concat(), "")
33 self.assertEqual(concat("str"), "str")
34 self.assertEqual(concat("str1", "str2"), "str1&str2")
35
36 self.assertEqual(concat("&", "?/"), "%26&%3F%2F")
37 self.assertEqual(
38 concat("GET", "http://example.org/", "foo=bar&baz=a"),
39 "GET&http%3A%2F%2Fexample.org%2F&foo%3Dbar%26baz%3Da"
40 )
41
42 def test_nonce(self, size=16):
43 nonce_values = set(oauth.nonce(size) for _ in range(size))
44
45 # uniqueness
46 self.assertEqual(len(nonce_values), size)
47
48 # length
49 for nonce in nonce_values:
50 self.assertEqual(len(nonce), size)
51
52 def test_quote(self):
53 quote = oauth.quote
54
55 reserved = ",;:!\"§$%&/(){}[]=?`´+*'äöü"
56 unreserved = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
57 "abcdefghijklmnopqrstuvwxyz"
58 "0123456789-._~")
59
60 for char in unreserved:
61 self.assertEqual(quote(char), char)
62
63 for char in reserved:
64 quoted = quote(char)
65 quoted_hex = quoted.replace("%", "")
66 self.assertTrue(quoted.startswith("%"))
67 self.assertTrue(len(quoted) >= 3)
68 self.assertEqual(quoted_hex.upper(), quoted_hex)
69
70 def test_generate_signature(self):
71 client = oauth.OAuth1Client(
72 CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
73
74 request = MockRequest()
75 params = []
76 self.assertEqual(
77 client.generate_signature(request, params),
78 "Wt2xo49dM5pkL4gsnCakNdHaVUo%3D")
79
80 request = MockRequest("https://example.org/")
81 params = [("hello", "world"), ("foo", "bar")]
82 self.assertEqual(
83 client.generate_signature(request, params),
84 "ay2269%2F8uKpZqKJR1doTtpv%2Bzn0%3D")
85
86 request = MockRequest("https://example.org/index.html"
87 "?hello=world&foo=bar", method="POST")
88 params = [("oauth_signature_method", "HMAC-SHA1")]
89 self.assertEqual(
90 client.generate_signature(request, params),
91 "yVZWb1ts4smdMmXxMlhaXrkoOng%3D")
92
93 def test_dunder_call(self):
94 client = oauth.OAuth1Client(
95 CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
96 request = MockRequest("https://example.org/")
97
98 with patch("time.time") as tmock, \
99 patch("gallery_dl.oauth.nonce") as nmock:
100 tmock.return_value = 123456789.123
101 nmock.return_value = "abcdefghijklmno"
102
103 client(request)
104
105 self.assertEqual(
106 request.headers["Authorization"],
107 """OAuth \
108 oauth_consumer_key="key",\
109 oauth_nonce="abcdefghijklmno",\
110 oauth_signature_method="HMAC-SHA1",\
111 oauth_timestamp="123456789",\
112 oauth_version="1.0",\
113 oauth_token="accesskey",\
114 oauth_signature="DjtTk5j5P3BDZFnstZ%2FtEYcwD6c%3D"\
115 """)
116
117 def test_request_token(self):
118 response = self._oauth_request(
119 "/request_token.php", {})
120 expected = "oauth_token=requestkey&oauth_token_secret=requestsecret"
121 self.assertEqual(response, expected, msg=response)
122
123 data = text.parse_query(response)
124 self.assertTrue(data["oauth_token"], REQUEST_TOKEN)
125 self.assertTrue(data["oauth_token_secret"], REQUEST_TOKEN_SECRET)
126
127 def test_access_token(self):
128 response = self._oauth_request(
129 "/access_token.php", {}, REQUEST_TOKEN, REQUEST_TOKEN_SECRET)
130 expected = "oauth_token=accesskey&oauth_token_secret=accesssecret"
131 self.assertEqual(response, expected, msg=response)
132
133 data = text.parse_query(response)
134 self.assertTrue(data["oauth_token"], ACCESS_TOKEN)
135 self.assertTrue(data["oauth_token_secret"], ACCESS_TOKEN_SECRET)
136
137 def test_authenticated_call(self):
138 params = {"method": "foo", "a": "äöüß/?&#", "äöüß/?&#": "a"}
139 response = self._oauth_request(
140 "/echo_api.php", params, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
141
142 self.assertEqual(text.parse_query(response), params)
143
144 def _oauth_request(self, endpoint, params=None,
145 oauth_token=None, oauth_token_secret=None):
146 # the test server at 'term.ie' is unreachable
147 raise unittest.SkipTest()
148
149 session = oauth.OAuth1Session(
150 CONSUMER_KEY, CONSUMER_SECRET,
151 oauth_token, oauth_token_secret,
152 )
153 try:
154 response = session.get(TESTSERVER + endpoint, params=params)
155 response.raise_for_status()
156 return response.text
157 except OSError:
158 raise unittest.SkipTest()
159
160
161 class MockRequest():
162
163 def __init__(self, url="", method="GET"):
164 self.url = url
165 self.method = method
166 self.headers = {}
167
168
169 if __name__ == "__main__":
170 unittest.main(warnings="ignore")