Example #1
0
 def test_valid_data(self):
     '''
     Test that when a valid email is provided that:
         - The users change_allowed attribute is set to False, change_email
           is set to the
         intended email, change_email_tracker to a time
         - That the status code is 200
         - That a html with information is rendered
     '''
     User.objects.create_user(email="*****@*****.**", password="******")
     self.user = User.objects.get(email="*****@*****.**")
     self.user.is_change_allowed = True
     self.user.save()
     self.sivanna = Client()
     self.sivanna.force_login(self.user)
     self.assertIsNone(self.user.change_email_tracker)
     response = self.sivanna.post("/change_email",
                                  {"email": "*****@*****.**"})
     self.assertEqual(response.status_code, 200)
     edited_user = User.objects.get(email="*****@*****.**")
     self.assertFalse(edited_user.is_change_allowed)
     self.assertEqual(edited_user.change_email, "*****@*****.**")
     self.assertIsNotNone(edited_user.change_email_tracker)
     msg = "We have sent a link to your new email: "\
           "<b>[email protected]</b>"
     self.assertContains(response, "{}".format(msg))
Example #2
0
class CancelOrderReasonTestCase(BaseTestCase):
    """
    Tests the functionality for submitting a cancel request reason
    """
    def setUp(self):
        """
        Initialize testing environment.
        """
        super(CancelOrderReasonTestCase, self).setUp()
        User.objects.create(email="*****@*****.**",
                            password="******")
        self.uriel = Client()
        user = User.objects.get(email="*****@*****.**")
        user.is_active = True
        user.save()
        self.uriel.force_login(user)

    def test_submit_reason_success(self):
        """
        Test user can successfuly submit a reason.
        """
        data = {'other_reason': 'I dont like the color.'}
        response = self.uriel.post('/submit_reason', data, follow=True)
        self.assertRedirects(response, '/', 302)

    def test_submit_form_with_error(self):
        """
        Test application does not allow form with error.
        """
        data = {'other_reason': '$$$$$$$$$$$$'}
        response = self.uriel.post('/submit_reason', data)
        self.assertEqual(response.request['PATH_INFO'], '/submit_reason')
Example #3
0
 def test_order_data_post_request(self):
     '''
     Test that if a user moves to the dashboard, and that he had made
         some orders and he posts something:
         - That the order details for his past orders are rendered:
     '''
     winniethepooh = Client()
     User.objects.create(email="*****@*****.**")
     user = User.objects.get(email="*****@*****.**")
     cart = Cart.objects.create(
         phone_model_item=self.samsung_note_5_rose_gold,
         quantity=3,
         owner=user)
     data = {
         'hidden_pickup': 1,
         'country_code': self.code.id,
         'phone_number': '0715557775',
         'location': 'Rongai, Posta'
     }
     winniethepooh.force_login(user)
     post_response = winniethepooh.post('/order', data, follow=True)
     order = Order.objects.get(owner=user)
     self.assertContains(post_response, cart.phone_model_item)
     self.assertContains(
         post_response,
         "<p><b>Order No:</b><span> #{}</span>".format(order.pk))
     self.assertContains(
         post_response, "<b>Payment Method:</b><span> {}</span>".format(
             order.payment_method))
     self.assertContains(
         post_response,
         "<b>Quantity:</b><span> {}</span>".format(order.quantity))
     self.assertContains(
         post_response, "<b>Total Price:</b><span> {}</span>".format(
             "{:,}".format(order.total_price)))
     self.assertContains(post_response,
                         "<span> {}</span>".format(order.status))
     order_date = order.date
     nairobi_time_zone = pytz.timezone('Africa/Nairobi')
     fmt = "%b %d %Y %H:%M"
     utc = order_date.replace(tzinfo=pytz.UTC)
     localtz = utc.astimezone(nairobi_time_zone)
     localtz = localtz.strftime(fmt)
     purchase_date = "<b>Purchase Date: </b><span>{}  : EAT</span>".\
         format(localtz)
     self.assertContains(post_response, purchase_date)
     self.assertContains(post_response,
                         "<li>Recipient: {}</li>".format(user))
     self.assertContains(
         post_response,
         "Location: {}".format(order.shipping_address.location))
     self.assertContains(
         post_response,
         "Pick up: {}".format(order.shipping_address.location))
     self.assertContains(
         post_response, "<li>Phone No: {}</li>".format(
             order.shipping_address.phone_number))
 def setUp(self):
     super(LogoutViewTest, self).setUp()
     self.flinstones = Client()
     user = User.objects.create_user(
         email='*****@*****.**',
         password='******',
         first_name='flinstones'
     )
     self.flinstones.force_login(user)
Example #5
0
 def test_not_logged_in(self):
     '''
     Test that when a user is not logged in:
         - That he is redirected to a log in page
     '''
     User.objects.create_user(email="*****@*****.**", password="******")
     self.user = User.objects.get(email="*****@*****.**")
     self.sivanna = Client()
     response = self.sivanna.get("/change_email")
     self.assertRedirects(response, "/login?next=/change_email", 302)
Example #6
0
 def setUp(self):
     """
     Set up test pre-conditions.
     """
     self.client = Client()
     user = User.objects.create_superuser(
         email='*****@*****.**',
         password='******',
     )
     self.client.force_login(user)
Example #7
0
 def test_change_allowed_false(self):
     '''
     Test that when a user is logged in and change allowed is False:
         - That the user is redirected to the confirm_user page
     '''
     User.objects.create_user(email="*****@*****.**", password="******")
     self.user = User.objects.get(email="*****@*****.**")
     self.sivanna = Client()
     self.sivanna.force_login(self.user)
     response = self.sivanna.get("/change_email")
     self.assertRedirects(response, "/confirm_user", 302)
Example #8
0
 def setUp(self):
     super(DashboardTemplate, self).setUp()
     user_data = UserSignupTestCase().generate_user_data({})
     response = self.client.post('/signup', user_data)
     html_content = "Please confirm your email address"
     self.assertContains(response, html_content)
     self.uriel = Client()
     user = User.objects.get(email="*****@*****.**")
     user.is_active = True
     user.save()
     self.uriel.force_login(user)
Example #9
0
 def setUp(self):
     """
     Initialize testing environment.
     """
     super(CancelOrderReasonTestCase, self).setUp()
     User.objects.create(email="*****@*****.**",
                         password="******")
     self.uriel = Client()
     user = User.objects.get(email="*****@*****.**")
     user.is_active = True
     user.save()
     self.uriel.force_login(user)
 def setUp(self):
     User.objects.create(
         email="*****@*****.**", first_name="Sivanna",
         last_name="Turimo", is_staff=False, is_active=True,
         is_change_allowed=False, phone_number=72200000,
         )
     self.user = User.objects.get(first_name="Sivanna")
     self.sivanna = Client()
     self.sivanna.force_login(self.user)
     self.function = Mock()
     self.request = RequestFactory()
     self.request.user = self.user
     super(DecoratorsTest, self).setUp()
Example #11
0
 def test_logged_in_change_allowed_true(self):
     '''
     Test that when a user is logged in and that change allowed is True:
         - That the user can view the page
     '''
     User.objects.create_user(email="*****@*****.**", password="******")
     self.user = User.objects.get(email="*****@*****.**")
     self.user.is_change_allowed = True
     self.user.save()
     self.sivanna = Client()
     self.sivanna.force_login(self.user)
     response = self.sivanna.get("/change_email")
     self.assertEqual(response.status_code, 200)
Example #12
0
 def test_wrong_email_format(self):
     '''
     Test that when an invalid email format is provided:
         - That an error is raised
     '''
     User.objects.create_user(email="*****@*****.**", password="******")
     self.user = User.objects.get(email="*****@*****.**")
     self.user.is_change_allowed = True
     self.user.save()
     self.sivanna = Client()
     self.sivanna.force_login(self.user)
     response = self.sivanna.post("/change_email", {"email": "pop@gmail"})
     self.assertEqual(response.status_code, 200)
     self.assertContains(response, EmailValidator.message)
 def setUp(self):
     super(LoginViewTest, self).setUp()
     self.bed_rock = Client()
     User.objects.create(email="*****@*****.**",
                         first_name="timon",
                         last_name="pumba",
                         is_staff=True,
                         is_active=True,
                         is_change_allowed=False,
                         country_code=self.code,
                         phone_number=722000000)
     self.timon = User.objects.get(email="*****@*****.**")
     self.timon.set_password("secret")
     self.timon.save()
class LoginViewTest(BaseTestCase):
    def setUp(self):
        super(LoginViewTest, self).setUp()
        self.bed_rock = Client()
        User.objects.create(email="*****@*****.**",
                            first_name="timon",
                            last_name="pumba",
                            is_staff=True,
                            is_active=True,
                            is_change_allowed=False,
                            country_code=self.code,
                            phone_number=722000000)
        self.timon = User.objects.get(email="*****@*****.**")
        self.timon.set_password("secret")
        self.timon.save()

    def test_next_on_login(self):
        """
        Test that if a user visits the login page with the next on
        the variable on the URL
            - That a successful login redirects to the URL specified
            on the next variable
        """
        login_data = {"email": "*****@*****.**", "password": "******"}
        response = self.bed_rock.post("/login?next=/dashboard", login_data)
        self.assertRedirects(response, "/dashboard")
Example #15
0
 def test_similar_email(self):
     '''
     Test that when a similar email to the user's original email is
     provided as a candidate for change:
         - That an error is raised
     '''
     User.objects.create_user(email="*****@*****.**", password="******")
     self.user = User.objects.get(email="*****@*****.**")
     self.user.is_change_allowed = True
     self.user.save()
     self.sivanna = Client()
     self.sivanna.force_login(self.user)
     response = self.sivanna.post("/change_email",
                                  {"email": "*****@*****.**"})
     self.assertEqual(response.status_code, 200)
     error_message = ChangeEmailForm.error_messages['invalid_email']
     self.assertContains(response, error_message)
     message = "Please provide new email for [email protected]"
     self.assertContains(response, message)
Example #16
0
 def test_existent_email(self):
     '''
     Test that when an existent email is provided:
         - That an error is raised
     '''
     # create another user with some credentials for testing
     User.objects.create_user(email="*****@*****.**", password="******")
     User.objects.create_user(email="*****@*****.**", password="******")
     self.user = User.objects.get(email="*****@*****.**")
     self.user.is_change_allowed = True
     self.user.save()
     self.sivanna = Client()
     self.sivanna.force_login(self.user)
     response = self.sivanna.post("/change_email",
                                  {"email": "*****@*****.**"})
     self.assertEqual(response.status_code, 200)
     error = "The email address you entered has already been registered."
     self.assertContains(response, "{}".format(error))
     message = "Please provide new email for [email protected]"
     self.assertContains(response, message)
Example #17
0
 def test_shipping_address_created(self):
     """
     Test that when the user places an order and the shipping address
     information is sent:
         - Their shipping data is saved
     """
     winniethepooh = Client()
     User.objects.create(email="*****@*****.**")
     order_user = User.objects.get(email="*****@*****.**")
     Cart.objects.create(phone_model_item=self.samsung_note_5_rose_gold,
                         quantity=3,
                         owner=order_user)
     data = {
         'hidden_pickup': 1,
         'country_code': self.code.id,
         'phone_number': '0715557775',
         'location': 'Rongai, Posta'
     }
     winniethepooh.force_login(order_user)
     post_response = winniethepooh.post('/order', data, follow=True)
     self.assertRedirects(post_response, '/dashboard#orders', 302)
Example #18
0
class AdminPage(TestCase):
    """Tests the admin page."""
    def setUp(self):
        """
        Set up test pre-conditions.
        """
        self.client = Client()
        user = User.objects.create_superuser(
            email='*****@*****.**',
            password='******',
        )
        self.client.force_login(user)

    def test_admin_title_exists(self):
        '''
        Test that the Title on the admin page is customized to Hirola Admin
        Panel and not Django adminstration.
        '''
        response = self.client.get('/admin/')
        self.assertContains(response, "Hirola Admin Panel")
        self.assertNotContains(response, "Django administration")
Example #19
0
 def test_order_to_pickup(self):
     """
     Test that a user can order to pickup from company premises
     """
     winniethepooh = Client()
     User.objects.create(email="*****@*****.**")
     user = User.objects.get(email="*****@*****.**")
     cart = Cart.objects.create(
         phone_model_item=self.samsung_note_5_rose_gold,
         quantity=3,
         owner=user)
     data = {}
     winniethepooh.force_login(user)
     post_response = winniethepooh.post('/order', data, follow=True)
     order = Order.objects.get(owner=user)
     self.assertContains(post_response, cart.phone_model_item)
     self.assertContains(
         post_response,
         "<p><b>Order No:</b><span> #{}</span>".format(order.pk))
     self.assertContains(post_response,
                         "<li>Recipient: {}</li>".format(user))
     self.assertContains(post_response, "Pick up: To Pick up")
Example #20
0
 def test_shipping_address_form_validation_failure(self):
     """
     Test that when the user places an order and the shipping address
     information sent is incorrect:
         - They are notified of the error
     """
     winniethepooh = Client()
     User.objects.create(email="*****@*****.**")
     order_user = User.objects.get(email="*****@*****.**")
     Cart.objects.create(phone_model_item=self.samsung_note_5_rose_gold,
                         quantity=3,
                         owner=order_user)
     data = {
         'hidden_pickup': 1,
         'country_code': self.code.id,
         'phone_number': '071555777578899',
         'location': 'Rongai, Posta'
     }
     winniethepooh.force_login(order_user)
     post_response = winniethepooh.post('/order', data)
     self.assertContains(post_response,
                         "The phone number entered is invalid.")
Example #21
0
class ChangeEmailView(BaseTestCase):
    """Tests functionality for changing email."""
    def setUp(self):
        """Set up initial state of tests."""
        super(ChangeEmailView, self).setUp()

    def test_not_logged_in(self):
        '''
        Test that when a user is not logged in:
            - That he is redirected to a log in page
        '''
        User.objects.create_user(email="*****@*****.**", password="******")
        self.user = User.objects.get(email="*****@*****.**")
        self.sivanna = Client()
        response = self.sivanna.get("/change_email")
        self.assertRedirects(response, "/login?next=/change_email", 302)

    def test_change_allowed_false(self):
        '''
        Test that when a user is logged in and change allowed is False:
            - That the user is redirected to the confirm_user page
        '''
        User.objects.create_user(email="*****@*****.**", password="******")
        self.user = User.objects.get(email="*****@*****.**")
        self.sivanna = Client()
        self.sivanna.force_login(self.user)
        response = self.sivanna.get("/change_email")
        self.assertRedirects(response, "/confirm_user", 302)

    def test_logged_in_change_allowed_true(self):
        '''
        Test that when a user is logged in and that change allowed is True:
            - That the user can view the page
        '''
        User.objects.create_user(email="*****@*****.**", password="******")
        self.user = User.objects.get(email="*****@*****.**")
        self.user.is_change_allowed = True
        self.user.save()
        self.sivanna = Client()
        self.sivanna.force_login(self.user)
        response = self.sivanna.get("/change_email")
        self.assertEqual(response.status_code, 200)

    def test_wrong_email_format(self):
        '''
        Test that when an invalid email format is provided:
            - That an error is raised
        '''
        User.objects.create_user(email="*****@*****.**", password="******")
        self.user = User.objects.get(email="*****@*****.**")
        self.user.is_change_allowed = True
        self.user.save()
        self.sivanna = Client()
        self.sivanna.force_login(self.user)
        response = self.sivanna.post("/change_email", {"email": "pop@gmail"})
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, EmailValidator.message)

    def test_existent_email(self):
        '''
        Test that when an existent email is provided:
            - That an error is raised
        '''
        # create another user with some credentials for testing
        User.objects.create_user(email="*****@*****.**", password="******")
        User.objects.create_user(email="*****@*****.**", password="******")
        self.user = User.objects.get(email="*****@*****.**")
        self.user.is_change_allowed = True
        self.user.save()
        self.sivanna = Client()
        self.sivanna.force_login(self.user)
        response = self.sivanna.post("/change_email",
                                     {"email": "*****@*****.**"})
        self.assertEqual(response.status_code, 200)
        error = "The email address you entered has already been registered."
        self.assertContains(response, "{}".format(error))
        message = "Please provide new email for [email protected]"
        self.assertContains(response, message)

    def test_similar_email(self):
        '''
        Test that when a similar email to the user's original email is
        provided as a candidate for change:
            - That an error is raised
        '''
        User.objects.create_user(email="*****@*****.**", password="******")
        self.user = User.objects.get(email="*****@*****.**")
        self.user.is_change_allowed = True
        self.user.save()
        self.sivanna = Client()
        self.sivanna.force_login(self.user)
        response = self.sivanna.post("/change_email",
                                     {"email": "*****@*****.**"})
        self.assertEqual(response.status_code, 200)
        error_message = ChangeEmailForm.error_messages['invalid_email']
        self.assertContains(response, error_message)
        message = "Please provide new email for [email protected]"
        self.assertContains(response, message)

    def test_valid_data(self):
        '''
        Test that when a valid email is provided that:
            - The users change_allowed attribute is set to False, change_email
              is set to the
            intended email, change_email_tracker to a time
            - That the status code is 200
            - That a html with information is rendered
        '''
        User.objects.create_user(email="*****@*****.**", password="******")
        self.user = User.objects.get(email="*****@*****.**")
        self.user.is_change_allowed = True
        self.user.save()
        self.sivanna = Client()
        self.sivanna.force_login(self.user)
        self.assertIsNone(self.user.change_email_tracker)
        response = self.sivanna.post("/change_email",
                                     {"email": "*****@*****.**"})
        self.assertEqual(response.status_code, 200)
        edited_user = User.objects.get(email="*****@*****.**")
        self.assertFalse(edited_user.is_change_allowed)
        self.assertEqual(edited_user.change_email, "*****@*****.**")
        self.assertIsNotNone(edited_user.change_email_tracker)
        msg = "We have sent a link to your new email: "\
              "<b>[email protected]</b>"
        self.assertContains(response, "{}".format(msg))
Example #22
0
 def setUp(self):
     User.objects.create_user(email="*****@*****.**", password="******")
     self.user = User.objects.get(email="*****@*****.**")
     self.sivanna = Client()
     super(ConfirmUserView, self).setUp()
Example #23
0
class ConfirmUserView(BaseTestCase):
    """Tests user confirmation view."""
    def setUp(self):
        User.objects.create_user(email="*****@*****.**", password="******")
        self.user = User.objects.get(email="*****@*****.**")
        self.sivanna = Client()
        super(ConfirmUserView, self).setUp()

    def test_login_required_for_confirm_user(self):
        '''
        Test that when a user is not logged in:
            - That he or she cannot access the confirm_user page link
        Test that when a user is logged in:
            - That he can access the confirm_user page link
        '''
        response = self.sivanna.get("/confirm_user")
        self.assertRedirects(response, "/login?next=/confirm_user", 302)

    def test_logged_in_access_confirm_user(self):
        '''
        Test that when a user is logged in:
            - That he can access the confirm_user page link
        '''
        self.sivanna.force_login(self.user)
        response = self.sivanna.get("/confirm_user")
        self.assertEqual(response.status_code, 200)

    def test_wrong_email_format(self):
        '''
        Test that when a wrong email format is granted:
            - That the page does not redirect.
            - That an error message is raised.
        '''
        self.sivanna.force_login(self.user)
        response = self.sivanna.post("/confirm_user", {
            "email": "pop@gmail",
            "password": "******"
        })
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, EmailValidator.message)

    def test_non_existent_email(self):
        '''
        Test that when a valid email format is entered but it does not
        exist that
            - The page does not redirect.
            - An error message is raised
        '''
        self.sivanna.force_login(self.user)
        response = self.sivanna.post("/confirm_user", {
            "email": "*****@*****.**",
            "password": "******"
        })
        self.assertEqual(response.status_code, 200)
        error_message = AuthenticationForm().error_messages['invalid_email']
        self.assertContains(response, error_message)

    def test_wrong_password(self):
        '''
        Test that when a valid email is entered with a wrong password that
            - The page does not redirect.
            - An error message is raised.
        '''
        self.sivanna.force_login(self.user)
        response = self.sivanna.post("/confirm_user", {
            "email": "*****@*****.**",
            "password": "******"
        })
        self.assertEqual(response.status_code, 200)
        error_message = AuthenticationForm().error_messages['invalid_login']
        self.assertContains(response, error_message)

    def test_valid_credentials(self):
        '''
        Test that when valid credentials are granted to the view:
            - That the page redirects
            - The the user's attribute 'is_change_allowed' changes to true
        '''
        self.sivanna.force_login(self.user)
        response = self.sivanna.post("/confirm_user", {
            "email": "*****@*****.**",
            "password": "******"
        })
        self.assertRedirects(response, "/change_email", 302)
        user = User.objects.get(email="*****@*****.**")
        self.assertEqual(user.is_change_allowed, True)
Example #24
0
class SearchTest(BaseTestCase):
    """Test search produces the expected results."""
    def setUp(self):
        User.objects.create_user(email="*****@*****.**", password="******")
        self.user = User.objects.get(email="*****@*****.**")
        self.sivanna = Client()
        super(SearchTest, self).setUp()

    def test_search_get_request(self):
        '''
        Test that when you use a get method to request for the search page
            - That the page redirects to the landing page
        '''
        response = self.sivanna.get("/search")
        self.assertContains(
            response, "Add something to the search bar to"
            " search for your items")

    def test_search_phone_name(self):
        '''
        Test that when you search for a phone name:
            - That the phone object is rendered on the search response
        '''
        response = self.sivanna.post("/search", {"search-name": "sam"})
        self.assertContains(response,
                            self.samsung_note_5_rose_gold.phone_model)

    def test_search_phone_price(self):
        '''
        Test that whe you search for a phone price:
            - That the phone object is rendered on the search response
        '''
        response = self.sivanna.post("/search", {"search-name": "25"})
        self.assertContains(response,
                            self.samsung_note_5_rose_gold.phone_model)

    def test_search_phone_size(self):
        '''
        Test that when you search for a phone price:
            - That the phone object is rendered on the search response
        '''
        response = self.sivanna.post("/search", {"search-name": "16"})
        self.assertContains(response,
                            self.samsung_note_5_rose_gold.phone_model)

    def test_search_phone_category(self):
        '''
        Test that when you enter a category name in the search bar:
            - That you get phone objects in that category
        '''
        response = self.sivanna.post("/search", {"search-name": "andro"})
        self.assertContains(response,
                            self.samsung_note_5_rose_gold.phone_model)
        self.assertContains(response,
                            self.samsung_note_7_rose_gold.phone_model)
        self.assertNotContains(response, self.iphone_6_s_rose_gold.phone_model)

    def test_search_phone_feature(self):
        '''
        Test that when you enter a phone feature in the search bar:
            - That you get phone objects with that feature
        '''

        Feature.objects.create(phone=self.samsung_note_7_rose_gold,
                               feature="6-inch screen")
        Feature.objects.create(phone=self.iphone_6_s_rose_gold,
                               feature="7-inch screen")
        response = self.sivanna.post("/search", {"search-name": "inch"})
        self.assertContains(response,
                            self.samsung_note_7_rose_gold.phone_model)
        self.assertContains(response, self.iphone_6_s_rose_gold.phone_model)
        self.assertNotContains(response,
                               self.samsung_note_5_rose_gold.phone_model)

    def test_search_product_information(self):
        '''
        Test that when you enter a phone product information in the \
            search bar:
            - That you get phone objects with that product information
        '''
        ProductInformation.objects.create(phone=self.samsung_note_7_rose_gold,
                                          feature="Network",
                                          value="GSM")
        ProductInformation.objects.create(phone=self.iphone_6_s_rose_gold,
                                          feature="Network",
                                          value="GSM")
        response = self.sivanna.post("/search", {"search-name": "gsm"})
        self.assertContains(response,
                            self.samsung_note_7_rose_gold.phone_model)
        self.assertContains(response, self.iphone_6_s_rose_gold.phone_model)
        self.assertNotContains(response,
                               self.samsung_note_5_rose_gold.phone_model)
        self.assertContains(response,
                            self.samsung_note_7_rose_gold.phone_model)
        self.assertContains(response, self.iphone_6_s_rose_gold.phone_model)
        self.assertNotContains(response,
                               self.samsung_note_5_rose_gold.phone_model)

    def test_search_product_review(self):
        '''
        Test that when you enter a phone review in the search bar:
            - That you get phone objects with that product information
        '''
        authentic_comment = "That was an authentic phone that I got"
        genuine_comment = "That was an genuine phone that I got"
        Review.objects.create(stars=5,
                              comments=authentic_comment,
                              phone_model=self.samsung_note_5,
                              owner=self.user)
        Review.objects.create(stars=4,
                              comments=genuine_comment,
                              phone_model=self.samsung_note_7,
                              owner=self.user)
        response = self.sivanna.post("/search", {"search-name": "genui"})
        self.assertNotContains(response,
                               self.samsung_note_5_rose_gold.phone_model)
        self.assertContains(response,
                            self.samsung_note_7_rose_gold.phone_model)
        self.assertNotContains(response, self.iphone_6_s_rose_gold.phone_model)
        response_2 = self.sivanna.post("/search", {"search-name": "auth"})
        self.assertContains(response_2,
                            self.samsung_note_5_rose_gold.phone_model)
        self.assertNotContains(response_2,
                               self.samsung_note_7_rose_gold.phone_model)
        self.assertNotContains(response_2,
                               self.iphone_6_s_rose_gold.phone_model)

    def test_not_in_stock_search(self):
        '''
        Test that for phones that are not in stock, or their quantity is zero:
            - They won't be rendered on search
        '''
        PhoneModel.objects.create(category=self.iphone,
                                  brand=self.apple_brand,
                                  brand_model="Iphone 6 J",
                                  average_review=5.0)
        self.iphone_6_j = PhoneModel.objects.get(brand_model="Iphone 6 J")
        PhoneModel.objects.create(category=self.iphone,
                                  brand=self.apple_brand,
                                  brand_model="Iphone 7 J",
                                  average_review=5.0)
        self.iphone_7_j = PhoneModel.objects.get(brand_model="Iphone 7 J")
        PhoneModelList.objects.create(phone_model=self.iphone_6_j,
                                      currency=self.currency_v,
                                      price=25000,
                                      size_sku=self.size_iphone,
                                      color=self.color_one,
                                      quantity=0,
                                      is_in_stock=True)
        self.iphone_6_s_rose_gold = PhoneModelList.objects.get(
            phone_model=self.iphone_6_s, color=self.color_one)
        PhoneModelList.objects.create(phone_model=self.iphone_7_j,
                                      currency=self.currency_v,
                                      price=25000,
                                      size_sku=self.size_iphone,
                                      color=self.color_one,
                                      quantity=4,
                                      is_in_stock=False)
        self.iphone_7_s_rose_gold = PhoneModelList.objects.get(
            phone_model=self.iphone_7_j, color=self.color_one)
        post_response_1 = self.client.post("/search",
                                           {"search-name": "Samsung Note 5"})
        post_response_3 = self.client.post("/search",
                                           {"search-name": "Iphone 6 J"})
        post_response_2 = self.client.post("/search",
                                           {"search-name": "Iphone 7"})
        self.assertContains(post_response_1, "Samsung Note 5")
        self.assertNotContains(post_response_2, "Iphone 7")
        self.assertNotContains(post_response_3, "Iphone 6")
class DashboardLogic(BaseTestCase):
    """Test that the dashboard behaves as expected."""

    def setUp(self):
        super(DashboardLogic, self).setUp()
        user_data = UserSignupTestCase().generate_user_data({})
        response = self.client.post('/signup', user_data)
        html_content = "Please confirm your email address"
        self.assertContains(response, html_content)
        self.uriel = Client()
        user = User.objects.get(email="*****@*****.**")
        user.is_active = True
        user.save()
        self.uriel.force_login(user)

    def test_name_edition(self):
        '''
        Test that when a logged in user edits his first and last name by
        entering the data correctly that:
            - The user remains on the dashboard page.
            - The first name is changed properly
            - The last name is changed properly
        '''
        first_name_data = {"first_name": "Britney"}
        response = self.uriel.post('/dashboard', first_name_data)
        self.assertEqual(response.status_code, 200)
        get_response = self.uriel.get('/dashboard')
        self.assertContains(get_response, "Britney")
        last_name_data = {"last_name": "Delila"}
        response = self.uriel.post('/dashboard', last_name_data)
        self.assertEqual(response.status_code, 200)
        get_response = self.uriel.get('/dashboard')
        self.assertContains(get_response, "Delila")

    def test_contact_edition(self):
        '''
        Test that when a logged in user edits his country code and phone
        number by entering the data correctly that:
            - The user remains on the dashboard page.
            - The country code is changed properly
            - The last name is changed properly
        '''
        CountryCode.objects.create(country_code=256, country="Uganda")
        country_code = CountryCode.objects.filter(country_code=256).first()
        country_code_data = {"country_code": country_code.id}
        response = self.uriel.post('/dashboard', country_code_data)
        self.assertEqual(response.status_code, 200)
        get_response = self.uriel.get('/dashboard')
        self.assertContains(get_response, str(country_code))
        phone_data = {"phone_number": 220000}
        response = self.uriel.post('/dashboard', phone_data)
        self.assertEqual(response.status_code, 200)
        get_response = self.uriel.get('/dashboard')
        self.assertContains(get_response, 220000)

    def test_old_password_validation(self):
        '''
        Test that when a user enters the wrong old password:
            - The user remains on the same page and is not redirected.
            - The user is prompted with an error message
        Test that when a user enters the correct old password:
            - The user is redirected to a page to edit the password
        '''
        response = self.uriel.post('/old_password', {
            "old_password": "******"
            })
        self.assertEqual(response.status_code, 200)
        error_message = "Your old password was entered incorrectly. "
        "Please enter it again."
        self.assertContains(response, error_message)
        response_1 = self.uriel.post('/old_password', {
            "old_password": "******"
            })
        self.assertRedirects(response_1, "/change_password", 302)

    def test_view_login_required(self):
        '''
        Test that if a user has not been logged in that:
            - He cannot access the dashboard view.
            - He cannot access the old password view.
            - He cannot access the change password view.
            - He is redirected to the login view
        '''
        old_password_view = self.client.get("/old_password")
        self.assertRedirects(
            old_password_view, "/login?next=/old_password", 302
            )
        dashboard_view = self.client.get('/dashboard')
        self.assertRedirects(
            dashboard_view, "/login?next=/dashboard", 302
            )
        change_password_view = self.client.get('/change_password')
        self.assertRedirects(
            change_password_view, "/login?next=/change_password", 302
            )

    def test_change_password_old_password_validation(self):
        '''
        Test that when a logged in user manually goes to the change_password
        view that:
            - He cannot access the view
            - He is redirected to the old_password view inorder to insert his
            old password.
        '''
        change_password_view = self.uriel.get('/change_password')
        self.assertRedirects(change_password_view, "/old_password", 302)

    def test_change_password(self):
        '''
        Test that when a user is changing a password that:
            - He is redirected to the login page
        '''
        self.uriel.post('/old_password', {"old_password": "******"})
        response = self.uriel.post('/change_password', {
            "new_password1": "!@£$!@£$!@£$£!@$!@£$!@3",
            "new_password2": "!@£$!@£$!@£$£!@$!@£$!@3"
            })
        self.assertRedirects(response, "/login", 302)
class LogoutViewTest(BaseTestCase):

    def setUp(self):
        super(LogoutViewTest, self).setUp()
        self.flinstones = Client()
        user = User.objects.create_user(
            email='*****@*****.**',
            password='******',
            first_name='flinstones'
        )
        self.flinstones.force_login(user)

    def test_logout_user(self):
        """
        Test that if a user has logged into a site and the user logs out
            - That his status changes to unauthenticated.
        """
        after_login_response = self.flinstones.get("/")
        self.assertTrue(after_login_response.context["user"].is_authenticated)
        self.flinstones.post("/logout")
        after_logout_response = self.flinstones.get("/")
        self.assertFalse(
            after_logout_response.context["user"].is_authenticated)

    def test_redirect_to_current_page_with_referer_header(self):
        """
        Test that if a user has logged out of any page on a browser that
        submits the HTTP_REFERER header
            - That he is redirected to the page he is on.
        """
        logout_response = self.flinstones.post("/logout", HTTP_REFERER="/help")
        self.assertRedirects(logout_response, "/help", 302)

    def test_redirect_to_home_page_without_referer_header(self):
        """
        Test that if a user has logged out of any page on a browser that does
        not submit the HTTP_REFERER header
            - That he is redirected to the home page.
        """
        get_help_response = self.flinstones.get("/help")
        self.assertEqual(get_help_response.request["PATH_INFO"], "/help")
        logout_response = self.flinstones.post("/logout")
        self.assertRedirects(logout_response, "/", 302)

    def test_user_name_disappears(self):
        """
        Test that if a user has logged out of any page
            - That the page he is redirected to does not contain his first
            name
        """
        after_login_response = self.flinstones.get("/")
        self.assertContains(after_login_response, 'flinstones')
        self.flinstones.post("/logout")
        after_logout_response = self.flinstones.get("/")
        self.assertNotContains(after_logout_response, 'flinstones')

    def test_logout_creates_session_key(self):
        """
        Test that logging out creates a session key
        """
        after_login_response = self.flinstones.get("/")
        self.assertTrue(after_login_response.context["user"].is_authenticated)
        self.assertTrue(self.flinstones.session.session_key)
        self.flinstones.post("/logout")
        after_logout_response = self.flinstones.get("/")
        self.assertFalse(
            after_logout_response.context["user"].is_authenticated)
        self.assertTrue(self.flinstones.session.session_key)
Example #27
0
class DashboardTemplate(BaseTestCase):
    def setUp(self):
        super(DashboardTemplate, self).setUp()
        user_data = UserSignupTestCase().generate_user_data({})
        response = self.client.post('/signup', user_data)
        html_content = "Please confirm your email address"
        self.assertContains(response, html_content)
        self.uriel = Client()
        user = User.objects.get(email="*****@*****.**")
        user.is_active = True
        user.save()
        self.uriel.force_login(user)

    def test_user_data_on_dashboard(self):
        '''
        Test that when a logged in user accesses the /dashboard page that:
            - The page contains all the Phone Categories of the site
            - The page contains Social media links
            - The user is able to see his or her Firstname, LastName, Phone
            number, Country Code, Country
        '''
        response = self.uriel.get('/dashboard')
        self.assertContains(response, "Iphone")
        self.assertContains(response, "Android")
        self.assertContains(response, "Tablet")
        self.assertContains(response, "Uriel")
        self.assertContains(response, "Timanko")
        self.assertContains(response, 722000000)
        self.assertContains(response, 254)
        self.assertContains(response, "Kenya")

    def test_review_data_on_dashboard(self):
        '''
        Test that when a logged in user accesses the dashboard that:
            - The user is able to view his or her reviews on an item he or she
            bought.
        '''
        (owner, order) = self.generate_review_data()
        data = {
            "stars": 5,
            "comments": "Great job guys",
            "owner": owner.id,
            "phone_model": self.samsung_note_5.id
        }
        response = self.elena.post('/admin/front/review/add/', data)
        self.assertEqual(response.status_code, 302)
        get_response = self.uriel.get('/dashboard')
        self.assertContains(
            get_response,
            "Great job guys",
        )

    def test_stars_counter(self):
        '''
        Test that when a user visits the dashboard view to view ratings:
            - That the stars are rendered properly in terms of checked and
            unchecked stars
        '''
        (owner, order) = self.generate_review_data()
        data = []
        for i in range(5):
            data.append({
                "stars": i + 1,
                "comments": "Great job guys",
                "owner": owner.id,
                "phone_model": self.iphone_6_s.id
            })
        checked_star = (
            "<i class=\"material-icons left checked\">grade</i>\n             "
            "               \n                            ")
        unchecked_star = (
            "<i class=\"material-icons left\">grade</i>\n      "
            "                      \n                            ")
        for i in range(5):
            self.elena.post('/admin/front/review/add/', data[i])
            response = self.uriel.get('/dashboard')
            self.assertContains(response, checked_star * (i + 1))
            self.assertContains(response, unchecked_star * (4 - i))
            Review.objects.get(stars=i + 1).delete()

    def test_order_data_get_request(self):
        '''
        Test that if a moves to the dashboard, and that he had made
        some orders
            - That the order details for his past orders are rendered:
        '''
        (owner, order) = self.generate_review_data()
        get_response = self.uriel.get('/dashboard')
        self.assertContains(get_response, order.phone.phone_model)
        self.assertContains(
            get_response,
            "<p><b>Order No:</b><span> #{}</span>".format(order.pk))
        self.assertContains(
            get_response, "<b>Payment Method:</b><span> {}</span>".format(
                order.payment_method))
        self.assertContains(
            get_response,
            "<b>Quantity:</b><span> {}</span>".format(order.quantity))
        self.assertContains(
            get_response, "<b>Total Price:</b><span> {}</span>".format(
                "{:,}".format(order.total_price)))
        self.assertContains(get_response,
                            "<span> {}</span>".format(order.status))
        order_date = order.date
        nairobi_time_zone = pytz.timezone('Africa/Nairobi')
        fmt = "%b %d %Y %H:%M"
        utc = order_date.replace(tzinfo=pytz.UTC)
        localtz = utc.astimezone(nairobi_time_zone)
        localtz = localtz.strftime(fmt)
        purchase_date = "<b>Purchase Date: </b><span>{}  : EAT</span>".\
            format(localtz)
        self.assertContains(get_response, purchase_date)
        self.assertContains(get_response,
                            "<li>Recipient: {}</li>".format(owner))
        self.assertContains(
            get_response,
            "Location: {}".format(order.shipping_address.location))
        self.assertContains(
            get_response,
            "<li>Pick up: {}</li>".format(order.shipping_address.location))

    def test_order_data_post_request(self):
        '''
        Test that if a user moves to the dashboard, and that he had made
            some orders and he posts something:
            - That the order details for his past orders are rendered:
        '''
        winniethepooh = Client()
        User.objects.create(email="*****@*****.**")
        user = User.objects.get(email="*****@*****.**")
        cart = Cart.objects.create(
            phone_model_item=self.samsung_note_5_rose_gold,
            quantity=3,
            owner=user)
        data = {
            'hidden_pickup': 1,
            'country_code': self.code.id,
            'phone_number': '0715557775',
            'location': 'Rongai, Posta'
        }
        winniethepooh.force_login(user)
        post_response = winniethepooh.post('/order', data, follow=True)
        order = Order.objects.get(owner=user)
        self.assertContains(post_response, cart.phone_model_item)
        self.assertContains(
            post_response,
            "<p><b>Order No:</b><span> #{}</span>".format(order.pk))
        self.assertContains(
            post_response, "<b>Payment Method:</b><span> {}</span>".format(
                order.payment_method))
        self.assertContains(
            post_response,
            "<b>Quantity:</b><span> {}</span>".format(order.quantity))
        self.assertContains(
            post_response, "<b>Total Price:</b><span> {}</span>".format(
                "{:,}".format(order.total_price)))
        self.assertContains(post_response,
                            "<span> {}</span>".format(order.status))
        order_date = order.date
        nairobi_time_zone = pytz.timezone('Africa/Nairobi')
        fmt = "%b %d %Y %H:%M"
        utc = order_date.replace(tzinfo=pytz.UTC)
        localtz = utc.astimezone(nairobi_time_zone)
        localtz = localtz.strftime(fmt)
        purchase_date = "<b>Purchase Date: </b><span>{}  : EAT</span>".\
            format(localtz)
        self.assertContains(post_response, purchase_date)
        self.assertContains(post_response,
                            "<li>Recipient: {}</li>".format(user))
        self.assertContains(
            post_response,
            "Location: {}".format(order.shipping_address.location))
        self.assertContains(
            post_response,
            "Pick up: {}".format(order.shipping_address.location))
        self.assertContains(
            post_response, "<li>Phone No: {}</li>".format(
                order.shipping_address.phone_number))

    def test_order_to_pickup(self):
        """
        Test that a user can order to pickup from company premises
        """
        winniethepooh = Client()
        User.objects.create(email="*****@*****.**")
        user = User.objects.get(email="*****@*****.**")
        cart = Cart.objects.create(
            phone_model_item=self.samsung_note_5_rose_gold,
            quantity=3,
            owner=user)
        data = {}
        winniethepooh.force_login(user)
        post_response = winniethepooh.post('/order', data, follow=True)
        order = Order.objects.get(owner=user)
        self.assertContains(post_response, cart.phone_model_item)
        self.assertContains(
            post_response,
            "<p><b>Order No:</b><span> #{}</span>".format(order.pk))
        self.assertContains(post_response,
                            "<li>Recipient: {}</li>".format(user))
        self.assertContains(post_response, "Pick up: To Pick up")

    def test_cancel_order(self):
        """
        Test user can cancel an order.
        """
        (owner, order) = self.generate_review_data()
        response = self.uriel.get('/cancel/{}'.format(order.pk))
        self.assertEqual(response.status_code, 200)
        cancelled_order = CancelledOrder.objects.get(owner=order.owner)
        self.assertEqual(order.quantity, cancelled_order.quantity)
        with self.assertRaises(Order.DoesNotExist):
            Order.objects.get(owner=owner)

    def test_cancel_non_existent_order(self):
        """
        Test that the app handles cancelling of a non existent order.
        """
        response = self.uriel.get('/cancel/12345', follow=True)
        self.assertRedirects(response, '/dashboard')
        message = list(response.context.get('messages'))[0]
        self.assertEqual(message.tags, 'error')
        s_msg = 'That order does not exist'
        self.assertTrue('{}'.format(s_msg) in message.message)

    def test_disable_cancel_order(self):
        """
        Test the request for disabling cancel order
        """
        (owner, order) = self.generate_review_data()
        data = {'order_id': order.id}
        response = self.client.get("/disable_cancel_order", data)
        msg = str(response.content, 'utf-8')
        self.assertIn(msg, 'Success!')
        order = Order.objects.get(owner=owner)
        self.assertFalse(order.is_cancellable)

    def test_disable_cancel_non_existent_order(self):
        """
        Test the request for disabling cancel order with
             a non existent order
        """
        (owner, order) = self.generate_review_data()
        data = {'order_id': 12345}
        response = self.client.get("/disable_cancel_order", data)
        msg = str(response.content, 'utf-8')
        self.assertIn(msg, 'Order not found')

    def test_confirm_cancel_page_rendered(self):
        """
        Test that when a user clicks on the cancel order button.
            that they are redirected to the confirm page.
        """
        (owner, order) = self.generate_review_data()
        data = {'order_id': order.id}
        response = self.client.get("/confirm/{}".format(order.id), data)
        page_header = '<h5>Confirm Order Cancellation</h5>'
        self.assertContains(response, page_header)

    def generate_review_data(self, shipping_address=None):
        """Generate data for a review."""
        owner = User.objects.get(email="*****@*****.**")
        OrderStatus.objects.create(status="Pending")
        status = OrderStatus.objects.get(status="Pending")
        address = ShippingAddress.objects.create(phone_number="0715557775",
                                                 country_code=self.code,
                                                 location="Kiambu Road",
                                                 pickup=True)
        Order.objects.create(owner=owner,
                             phone=self.samsung_note_5_rose_gold,
                             status=status,
                             quantity=2,
                             total_price=80000,
                             shipping_address=address)
        order = Order.objects.get(owner=owner)
        return (owner, order)
class DecoratorsTest(BaseTestCase):
    """Test that app decorators function as expected."""
    def setUp(self):
        User.objects.create(
            email="*****@*****.**", first_name="Sivanna",
            last_name="Turimo", is_staff=False, is_active=True,
            is_change_allowed=False, phone_number=72200000,
            )
        self.user = User.objects.get(first_name="Sivanna")
        self.sivanna = Client()
        self.sivanna.force_login(self.user)
        self.function = Mock()
        self.request = RequestFactory()
        self.request.user = self.user
        super(DecoratorsTest, self).setUp()

    def test_is_change_allowed_decorator_false(self):
        '''
        Test that when a mock function and a request with a user whose
        'is_change_allowed' attribute is set to False is granted to a
        decorator function that:
            - The response redirects to the confirm user page
        '''
        self.assertEqual(self.request.user.is_change_allowed, False)
        decorator = is_change_allowed_required(self.function)
        response = decorator(self.request)
        response.client = self.sivanna
        self.assertRedirects(response, "/confirm_user", 302)

    def test_is_change_allowed_decorator_true(self):
        '''
        Test that when a mock function and a request with a user whose
        'is_change_allowed' attribute is set to True is granted to a decorator
        function that:
            - The response returns the mock function provided
        '''
        request = self.request
        request.user.is_change_allowed = True
        self.assertEqual(self.request.user.is_change_allowed, True)
        decorator = is_change_allowed_required(self.function)
        response = decorator(request)
        self.assertEqual(isinstance(response, Mock), True)

    def test_old_password_required_decorator_false(self):
        '''
        Test that when a mock function and a request with a user whose
        'is_change_allowed' attribute is set to False is granted to a
        decorator function that:
            - The response redirects to the confirm user page
        '''
        self.assertEqual(self.request.user.is_change_allowed, False)
        decorator = old_password_required(self.function)
        response = decorator(self.request)
        response.client = self.sivanna
        self.assertRedirects(response, "/old_password", 302)

    def test_old_password_required_decorator_true(self):
        '''
        Test that when a mock function and a request with a user whose
        'is_change_allowed' attribute is set to True is granted to a decorator
        function that:
            - The response returns the mock function provided
        '''
        request = self.request
        request.user.is_change_allowed = True
        self.assertEqual(self.request.user.is_change_allowed, True)
        decorator = old_password_required(self.function)
        response = decorator(request)
        self.assertEqual(isinstance(response, Mock), True)