2
2
3
3
import json
4
4
5
- from django .test import TestCase , RequestFactory
6
5
from django .core .urlresolvers import reverse
6
+ from django .test import TestCase , RequestFactory
7
+ from django .views .generic import View
8
+
9
+ from oauthlib .oauth2 import BackendApplicationServer
7
10
8
11
from ..compat import get_user_model
9
12
from ..models import Application
13
+ from ..oauth2_validators import OAuth2Validator
10
14
from ..settings import oauth2_settings
11
15
from ..views import ProtectedResourceView
12
-
16
+ from .. views . mixins import OAuthLibMixin
13
17
from .test_utils import TestCaseUtils
14
18
15
19
@@ -53,6 +57,7 @@ def test_client_credential_access_allowed(self):
53
57
54
58
response = self .client .post (reverse ('token' ), data = token_request_data , ** auth_headers )
55
59
self .assertEqual (response .status_code , 200 )
60
+
56
61
content = json .loads (response .content .decode ("utf-8" ))
57
62
access_token = content ['access_token' ]
58
63
@@ -66,3 +71,44 @@ def test_client_credential_access_allowed(self):
66
71
view = ResourceView .as_view ()
67
72
response = view (request )
68
73
self .assertEqual (response , "This is a protected resource" )
74
+
75
+
76
+ class TestExtendedRequest (BaseTest ):
77
+ @classmethod
78
+ def setUpClass (cls ):
79
+ cls .request_factory = RequestFactory ()
80
+
81
+ def test_extended_request (self ):
82
+ class TestView (OAuthLibMixin , View ):
83
+ server_class = BackendApplicationServer
84
+ validator_class = OAuth2Validator
85
+
86
+ def get_scopes (self ):
87
+ return ['read' , 'write' ]
88
+
89
+ token_request_data = {
90
+ 'grant_type' : 'client_credentials' ,
91
+ }
92
+ auth_headers = self .get_basic_auth_header (self .application .client_id , self .application .client_secret )
93
+ response = self .client .post (reverse ('token' ), data = token_request_data , ** auth_headers )
94
+ self .assertEqual (response .status_code , 200 )
95
+
96
+ content = json .loads (response .content .decode ("utf-8" ))
97
+ access_token = content ['access_token' ]
98
+
99
+ # use token to access the resource
100
+ auth_headers = {
101
+ 'HTTP_AUTHORIZATION' : 'Bearer ' + access_token ,
102
+ }
103
+
104
+ request = self .request_factory .get ("/fake-req" , ** auth_headers )
105
+ request .user = "fake"
106
+
107
+ test_view = TestView ()
108
+ self .assertIsInstance (test_view .get_server (), BackendApplicationServer )
109
+
110
+ valid , r = test_view .verify_request (request )
111
+ self .assertTrue (valid )
112
+ self .assertEqual (r .user , self .dev_user )
113
+ self .assertEqual (r .client , self .application )
114
+ self .assertEqual (r .scopes , ['read' , 'write' ])
0 commit comments