class ViewExternalLoginTests(TestCase): @classmethod def setUpTestData(cls): # Set up data for the whole TestCase cls.new_user: User = User.objects.create( email="*****@*****.**", membership_started_at=datetime.now() - timedelta(days=5), membership_expires_at=datetime.now() + timedelta(days=5), slug="ujlbu4" ) def setUp(self): self.client = HelperClient() def test_successful_flat_redirect(self): # given self.client = HelperClient(user=self.new_user) self.client.authorise() # when with self.settings(JWT_PRIVATE_KEY=JWT_STUB_VALUES.JWT_PRIVATE_KEY): response = self.client.get(reverse('external_login'), data={'redirect': 'some-page'}) # then self.assertRegex(text=urljoin(response.request['PATH_INFO'], response.url), expected_regex='\/auth\/external\/some-page\?jwt=.*') # check jwt url_params = response.url.split("?")[1] jwt_str = url_params.split("=")[1] payload = jwt.decode(jwt_str, verify=False) self.assertIsNotNone(payload) self.assertEqual(payload['user_slug'], self.new_user.slug) self.assertEqual(payload['user_name'], self.new_user.full_name) self.assertIsNotNone(payload['exp']) def test_successful_redirect_with_query_params(self): # given self.client = HelperClient(user=self.new_user) self.client.authorise() # when with self.settings(JWT_PRIVATE_KEY=JWT_STUB_VALUES.JWT_PRIVATE_KEY): response = self.client.get(reverse('external_login'), data={'redirect': 'some-page?param1=value1'}) # then self.assertRegex(text=urljoin(response.request['PATH_INFO'], response.url), expected_regex='\/auth\/external\/some-page\?param1=value1&jwt=.*') def test_param_redirect_absent(self): response = self.client.get(reverse('external_login')) self.assertContains(response=response, text="Нужен параметр ?redirect", status_code=200) def test_user_is_unauthorised(self): response = self.client.get(reverse('external_login'), data={'redirect': 'some-page'}) self.assertRedirects(response=response, expected_url='/auth/login/?goto=%2Fauth%2Fexternal%2F%3Fredirect%3Dsome-page', fetch_redirect_response=False) self.assertFalse(self.client.is_authorised())
def test_membership_already_expired(self): # given new_user: User = User.objects.create( email="*****@*****.**", membership_started_at=datetime.now() - timedelta(days=10), membership_expires_at=datetime.now() - timedelta(days=5), slug="ujlbu4") client = HelperClient(user=new_user) client.authorise() # when response = client.get(reverse('membership_expired')) self.assertContains(response=response, text="Ваша клубная карта истекла", status_code=200)
def test_membership_expires_future(self): # given new_user: User = User.objects.create( email="*****@*****.**", membership_started_at=datetime.now() - timedelta(days=5), membership_expires_at=datetime.now() + timedelta(days=5), slug="ujlbu4") client = HelperClient(user=new_user) client.authorise() # when response = client.get(reverse('membership_expired')) self.assertRedirects(response=response, expected_url=f'/user/{new_user.slug}/', fetch_redirect_response=False)
class TestPayView(TestCase): @classmethod def setUpTestData(cls): cls.existed_user: User = User.objects.create( email="*****@*****.**", membership_started_at=datetime.now() - timedelta(days=5), membership_expires_at=datetime.now() + timedelta(days=5), slug="ujlbu4") def setUp(self): self.client = HelperClient(user=self.existed_user) def test_positive_new_user(self, mocked_stripe): # given product_code = "club1" email = f"new-user-{uuid.uuid4()}@email.com" StripeSession = namedtuple('Session', "id") session = StripeSession(id=f"{uuid.uuid4()}") mocked_stripe.checkout.Session.create.return_value = session # when response = self.client.get( reverse("pay"), data={ "product_code": product_code, # "is_recurrent": PRODUCTS[product_code]["recurrent"], "email": email }) # check self.assertTrue(User.objects.filter(email=email).exists(), ) created_user: User = User.objects.get(email=email) self.assertEqual(created_user.email, email) self.assertEqual(created_user.membership_platform_type, User.MEMBERSHIP_PLATFORM_DIRECT) self.assertEqual(created_user.full_name, email.replace("@email.com", "")) self.assertAlmostEquals(created_user.membership_started_at, datetime.utcnow(), delta=timedelta(seconds=5)) self.assertAlmostEquals(created_user.membership_expires_at, datetime.utcnow(), delta=timedelta(seconds=5)) self.assertEqual(created_user.moderation_status, User.MODERATION_STATUS_INTRO) self.assertTrue(Payment.get(reference=session.id)) self.assertContains(response=response, text="Платим 💰", status_code=200) def test_positive_existed_authorised_user(self, mocked_stripe): # given product_code = "club1" StripeSession = namedtuple('Session', "id") session = StripeSession(id=f"{uuid.uuid4()}") mocked_stripe.checkout.Session.create.return_value = session self.client.authorise() # when response = self.client.get(reverse("pay"), data={ "product_code": product_code, }) # check self.assertTrue( User.objects.filter(email=self.existed_user.email).exists(), ) user_after: User = User.objects.get(email=self.existed_user.email) self.assertEqual(user_after.membership_platform_type, self.existed_user.membership_platform_type) self.assertEqual(user_after.full_name, self.existed_user.full_name) self.assertEqual(user_after.membership_started_at, self.existed_user.membership_started_at) self.assertAlmostEquals(user_after.membership_expires_at, self.existed_user.membership_expires_at) self.assertEqual(user_after.moderation_status, self.existed_user.moderation_status) self.assertTrue(Payment.get(reference=session.id)) self.assertContains(response=response, text="Платим 💰", status_code=200) def test_negative_new_user_with_broken_email(self, mocked_stripe): # given product_code = "club1" broken_email = f"email-invalid" # when response = self.client.get(reverse("pay"), data={ "product_code": product_code, "email": broken_email }) # check self.assertFalse(User.objects.filter(email=broken_email).exists(), ) self.assertContains(response=response, text="Плохой e-mail адрес", status_code=200) def test_product_not_found(self, mocked_stripe): product_code = "unexisted-product-code" # when response = self.client.get(reverse("pay"), data={ "product_code": product_code, }) # check self.assertContains(response=response, text="Не выбран пакет", status_code=200)
def _authorized_client(user): client = HelperClient(user) if user is not None: client.authorise() return client
class ViewsAuthTests(TestCase): @classmethod def setUpTestData(cls): # Set up data for the whole TestCase cls.new_user: User = User.objects.create( email="*****@*****.**", membership_started_at=datetime.now() - timedelta(days=5), membership_expires_at=datetime.now() + timedelta(days=5), slug="ujlbu4" ) def setUp(self): self.client = HelperClient(user=self.new_user) def test_join_anonymous(self): response = self.client.get(reverse('join')) # check auth/join.html is rendered self.assertContains(response=response, text="Всегда рады новым членам", status_code=200) def test_join_authorised(self): self.client.authorise() response = self.client.get(reverse('join')) self.assertRedirects(response=response, expected_url=f'/user/{self.new_user.slug}/', fetch_redirect_response=False) def test_login_anonymous(self): response = self.client.get(reverse('login')) # check auth/join.html is rendered self.assertContains(response=response, text="Вход по почте или нику", status_code=200) def test_login_authorised(self): self.client.authorise() response = self.client.get(reverse('login')) self.assertRedirects(response=response, expected_url=f'/user/{self.new_user.slug}/', fetch_redirect_response=False) def test_logout_success(self): self.client.authorise() response = self.client.post(reverse('logout')) self.assertRedirects(response=response, expected_url=f'/', fetch_redirect_response=False) self.assertFalse(self.client.is_authorised()) def test_logout_unauthorised(self): response = self.client.post(reverse('logout')) self.assertTrue(self.client.is_access_denied(response)) def test_logout_wrong_method(self): self.client.authorise() response = self.client.get(reverse('logout')) self.assertEqual(response.status_code, HttpResponseNotAllowed.status_code) response = self.client.put(reverse('logout')) self.assertEqual(response.status_code, HttpResponseNotAllowed.status_code) response = self.client.delete(reverse('logout')) self.assertEqual(response.status_code, HttpResponseNotAllowed.status_code) def test_debug_dev_login_unauthorised(self): response = self.client.post(reverse('debug_dev_login')) self.assertTrue(self.client.is_authorised()) me = self.client.print_me() self.assertIsNotNone(me['id']) self.assertEqual(me['email'], '*****@*****.**') self.assertTrue(me['is_email_verified']) self.assertTrue(me['slug'], 'dev') self.assertEqual(me['moderation_status'], 'approved') self.assertEqual(me['roles'], ['god']) # todo: check created post (intro) def test_debug_dev_login_authorised(self): self.client.authorise() response = self.client.post(reverse('debug_dev_login')) self.assertTrue(self.client.is_authorised()) me = self.client.print_me() self.assertTrue(me['slug'], self.new_user.slug) def test_debug_random_login_unauthorised(self): response = self.client.post(reverse('debug_random_login')) self.assertTrue(self.client.is_authorised()) me = self.client.print_me() self.assertIsNotNone(me['id']) self.assertIn('@random.dev', me['email']) self.assertTrue(me['is_email_verified']) self.assertEqual(me['moderation_status'], 'approved') self.assertEqual(me['roles'], [])
class ViewExternalLoginTests(TestCase): @classmethod def setUpTestData(cls): # Set up data for the whole TestCase cls.new_user: User = User.objects.create( email="*****@*****.**", membership_started_at=datetime.now() - timedelta(days=5), membership_expires_at=datetime.now() + timedelta(days=5), slug="ujlbu4") cls.app: Apps = Apps.objects.create( id="test", name="test", jwt_secret=JWT_STUB_VALUES.JWT_PRIVATE_KEY, jwt_algorithm="RS256", jwt_expire_hours=1, redirect_urls=["https://some-page"], ) def setUp(self): self.client = HelperClient() def test_successful_flat_redirect(self): # given self.client = HelperClient(user=self.new_user) self.client.authorise() # when response = self.client.get(reverse('external_login'), data={ 'redirect': 'https://some-page', 'app_id': 'test' }) # then self.assertRegex(text=urljoin(response.request['PATH_INFO'], response.url), expected_regex='https://some-page\?jwt=.*') # check jwt url_params = response.url.split("?")[1] jwt_str = url_params.split("=")[1] payload = jwt.decode(jwt_str, verify=False) self.assertIsNotNone(payload) self.assertEqual(payload['user_slug'], self.new_user.slug) self.assertEqual(payload['user_name'], self.new_user.full_name) self.assertIsNotNone(payload['exp']) def test_successful_redirect_with_query_params(self): # given self.client = HelperClient(user=self.new_user) self.client.authorise() # when response = self.client.get(reverse('external_login'), data={ 'redirect': 'https://some-page?param1=value1', 'app_id': 'test' }) # then self.assertRegex( text=urljoin(response.request['PATH_INFO'], response.url), expected_regex='https://some-page\?param1=value1&jwt=.*') def test_param_wrong_app_id(self): self.client = HelperClient(user=self.new_user) self.client.authorise() response = self.client.get(reverse('external_login'), data={ 'app_id': 'UNKNOWN', 'redirect': 'https://some-page' }) self.assertContains( response=response, text="Неизвестное приложение, проверьте параметр ?app_id", status_code=400) def test_param_redirect_absent(self): self.client = HelperClient(user=self.new_user) self.client.authorise() response = self.client.get(reverse('external_login'), data={'app_id': 'test'}) self.assertContains(response=response, text="Нужен параметр ?redirect", status_code=400) def test_user_is_unauthorised(self): response = self.client.get(reverse('external_login'), data={ 'redirect': 'some-page', 'app_id': 'test' }) self.assertRedirects( response=response, expected_url= '/auth/login/?goto=%2Fauth%2Fexternal%2F%3Fredirect%3Dsome-page', fetch_redirect_response=False) self.assertFalse(self.client.is_authorised())