11from datetime import datetime , timedelta
22from http .cookies import SimpleCookie
3+ from unittest .mock import call , patch
34
45import pytest
56from django .conf import settings
67from django .test import TestCase , TransactionTestCase , override_settings
78from django .urls import ResolverMatch
89from rest_framework .exceptions import AuthenticationFailed , PermissionDenied
910from rest_framework .test import APIRequestFactory
11+ from shared .django_apps .core .tests .factories import RepositoryFactory
1012
1113from codecov_auth .authentication import (
1214 InternalTokenAuthentication ,
@@ -168,7 +170,7 @@ def test_bearer_token_default_token_envar_and_same_string_as_header(self):
168170class ImpersonationTests (TransactionTestCase ):
169171 def setUp (self ):
170172 self .owner_to_impersonate = OwnerFactory (
171- username = "impersonateme" , service = "github"
173+ username = "impersonateme" , service = "github" , user = UserFactory ( is_staff = False )
172174 )
173175 self .staff_user = UserFactory (is_staff = True )
174176 self .non_staff_user = UserFactory (is_staff = False )
@@ -184,6 +186,47 @@ def test_impersonation(self):
184186 )
185187 assert res .json ()["data" ]["me" ] == {"user" : {"username" : "impersonateme" }}
186188
189+ @patch ("core.commands.repository.repository.RepositoryCommands.fetch_repository" )
190+ def test_impersonation_with_okta (self , mock_call_to_fetch_repository ):
191+ repo = RepositoryFactory (author = self .owner_to_impersonate , private = True )
192+ query_repositories = """{ owner(username: "%s") { repository(name: "%s") { ... on Repository { name } } } }"""
193+ query = query_repositories % (repo .author .username , repo .name )
194+
195+ # not impersonating
196+ del self .client .cookies ["staff_user" ]
197+ self .client .force_login (user = self .owner_to_impersonate .user )
198+ self .client .post (
199+ "/graphql/gh" ,
200+ {"query" : query },
201+ content_type = "application/json" ,
202+ )
203+
204+ # impersonating, same query
205+ self .client .cookies = SimpleCookie ({"staff_user" : self .owner_to_impersonate .pk })
206+ self .client .force_login (user = self .staff_user )
207+ self .client .post (
208+ "/graphql/gh" ,
209+ {"query" : query },
210+ content_type = "application/json" ,
211+ )
212+
213+ mock_call_to_fetch_repository .assert_has_calls (
214+ [
215+ call (
216+ self .owner_to_impersonate ,
217+ repo .name ,
218+ [],
219+ exclude_okta_enforced_repos = True ,
220+ ),
221+ call (
222+ self .owner_to_impersonate ,
223+ repo .name ,
224+ [],
225+ exclude_okta_enforced_repos = False ,
226+ ),
227+ ]
228+ )
229+
187230 def test_impersonation_non_staff (self ):
188231 self .client .force_login (user = self .non_staff_user )
189232 with pytest .raises (PermissionDenied ):
0 commit comments