Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update tests.py #717

Merged
merged 6 commits into from
Jun 16, 2023
Merged

Update tests.py #717

merged 6 commits into from
Jun 16, 2023

Conversation

josh-bristow
Copy link
Contributor

@josh-bristow josh-bristow commented Jun 15, 2023

Closes #681

Unit Tests for Cart Functionality

This pull request adds comprehensive unit tests for the Cart class in the cart.py module. The tests cover various scenarios to ensure the correctness and robustness of the Cart implementation.

The test cases included in this pull request are as follows:

Cart Initialization Test: This test verifies that the cart is properly initialized and empty when a request is made.

Add Product Test: This test checks the functionality of adding products to the cart, including verifying the correct quantity and subtotal price calculations.

Save Cart Test: This test ensures that the cart is marked as modified after it is saved.

Remove Product Test: This test validates the ability to remove products from the cart and confirms that the cart is empty after removal.

Get Cart Products Test: This test checks if the get_cart_products method returns the expected list of products in the cart.

Get Subtotal Price Test: This test verifies the accuracy of calculating the subtotal price of all products in the cart.

Get Shipping Cost Test: This test ensures that the get_shipping_cost method returns the correct shipping cost based on the contents of the cart. (Please note that the expected shipping cost value needs to be provided.)

Cart Iteration Test: This test validates that iterating over the cart items returns the correct product details, including quantity, price, and total price.

These tests are designed to cover different aspects of the Cart functionality, including initialization, adding/removing products, calculating prices, and iterating over cart items. They provide comprehensive coverage to catch any potential bugs or issues in the Cart implementation.

Please review these unit tests and let me know if any further changes or additions are required.

Unit Tests for Cart Functionality

This pull request adds comprehensive unit tests for the Cart class in the cart.py module. The tests cover various scenarios to ensure the correctness and robustness of the Cart implementation.

The test cases included in this pull request are as follows:

Cart Initialization Test: This test verifies that the cart is properly initialized and empty when a request is made.

Add Product Test: This test checks the functionality of adding products to the cart, including verifying the correct quantity and subtotal price calculations.

Save Cart Test: This test ensures that the cart is marked as modified after it is saved.

Remove Product Test: This test validates the ability to remove products from the cart and confirms that the cart is empty after removal.

Get Cart Products Test: This test checks if the get_cart_products method returns the expected list of products in the cart.

Get Subtotal Price Test: This test verifies the accuracy of calculating the subtotal price of all products in the cart.

Get Shipping Cost Test: This test ensures that the get_shipping_cost method returns the correct shipping cost based on the contents of the cart. (Please note that the expected shipping cost value needs to be provided.)

Cart Iteration Test: This test validates that iterating over the cart items returns the correct product details, including quantity, price, and total price.

These tests are designed to cover different aspects of the Cart functionality, including initialization, adding/removing products, calculating prices, and iterating over cart items. They provide comprehensive coverage to catch any potential bugs or issues in the Cart implementation.

Please review these unit tests and let me know if any further changes or additions are required.
Copy link
Member

@brylie brylie left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Really great work!

@brylie
Copy link
Member

brylie commented Jun 15, 2023

@josh-bristow, we're really in need of improved test coverage like you have provided in this pull request. Thank you so much. :-)

Would you be able to help out with some other unit-test coverage issues? I've labeled them as help wanted and good first issue in our backlog:

https://github.com/WesternFriend/WF-website/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22

Copy link
Member

@brylie brylie left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh no! For some reason, when the tests run, there are several errors:

AttributeError: 'WSGIRequest' object has no attribute 'session'

Did the tests run successfully in your local branch with python manage.py test?

Let's see if we can resolve those errors so the test will pass by manually specifying the session property.

Session and authentication attributes must be supplied by the test itself if required for the view to function properly.

https://stackoverflow.com/a/17020518/1191545

cart/tests.py Outdated Show resolved Hide resolved
Co-authored-by: Brylie Christopher Oxley <[email protected]>
Copy link
Member

@brylie brylie left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests still seem to be failing. Please make sure you can run the tests locally with python manage.py test cart and that they all pass successfully.

@brylie
Copy link
Member

brylie commented Jun 15, 2023

I think the errors in the tests are due to the test ‘client’ not having a session when making the request. There are some Stack Overflow threads and possibly official documentation for adding a ‘session’ object to the test client.

@brylie

This comment was marked as outdated.

@brylie
Copy link
Member

brylie commented Jun 15, 2023

ChatGPT recommends using the Django test Client.

The Django test Client includes session data by default. Here's how you could rewrite the test to use Client instead of RequestFactory:

from django.test import TestCase, Client
from unittest.mock import patch
from .models import Product  # import the Product model
from .cart import Cart  # import your Cart class
from decimal import Decimal

class CartTestCase(TestCase):

    def setUp(self):
        self.client = Client()
        self.product_mock = Product(id=1, title='product1', price=Decimal(10.00))

    @patch.object(Product.objects, 'filter')
    def test_add_product(self, mock_filter):
        mock_filter.return_value = [self.product_mock]
        session = self.client.session
        cart = Cart(session)
        cart.add(self.product_mock, quantity=2, update_quantity=False)

        expected_cart = {
            str(self.product_mock.id): {
                "product_title": self.product_mock.title,
                "product_id": str(self.product_mock.id),
                "quantity": 2,
                "price": str(self.product_mock.price),
            }
        }

        self.assertEqual(cart.cart, expected_cart)

The test Client allows you to interact with your application in a simple way, providing several methods to simulate various HTTP requests and also to create a session for an anonymous user. The key difference is that we're passing the session directly to the Cart instance, as opposed to passing a request object. This should work assuming your Cart class can handle being initialized with a session object directly.

@brylie
Copy link
Member

brylie commented Jun 15, 2023

ChatGPT:

The @patch.object() decorator from the unittest.mock module is used to replace a method or attribute on an object during a test.

In the context of Django and testing, this is typically used to replace complex behavior such as database queries, calls to external services, or other functions that you don't want to actually execute during a test. Instead, you want to simulate or "mock" their behavior. This allows you to test your own code in isolation, without depending on external systems or side effects.

When you use @patch.object(), you provide two arguments:

  1. The object you want to patch (for example, Product.objects).
  2. The name of the attribute or method you want to replace (for example, 'filter').

For example, @patch.object(Product.objects, 'filter') would replace the filter method on Product.objects with a MagicMock object for the duration of the test.

The patch.object() decorator also passes this new mock object as an argument to your test method, allowing you to control its behavior. For example, you can set return_value to specify what the mock object should return when it's called.

In the provided code, this is used to simulate the behavior of the filter method on Product.objects without having to actually run a database query. Instead, the test controls exactly what the method returns, allowing it to focus on testing the behavior of the Cart class.

@sonarcloud
Copy link

sonarcloud bot commented Jun 16, 2023

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 1 Code Smell

No Coverage information No Coverage information
0.0% 0.0% Duplication

@codeclimate
Copy link

codeclimate bot commented Jun 16, 2023

Code Climate has analyzed commit c164f53 and detected 0 issues on this pull request.

The test coverage on the diff in this pull request is 87.5% (50% is the threshold).

This pull request will bring the total coverage in the repository to 67.4% (1.2% change).

View more on Code Climate.

@codecov
Copy link

codecov bot commented Jun 16, 2023

Codecov Report

Patch coverage: 87.50% and project coverage change: +1.18 🎉

Comparison is base (8d76f3e) 66.26% compared to head (c164f53) 67.45%.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #717      +/-   ##
==========================================
+ Coverage   66.26%   67.45%   +1.18%     
==========================================
  Files          99       99              
  Lines        2911     2916       +5     
==========================================
+ Hits         1929     1967      +38     
+ Misses        982      949      -33     
Impacted Files Coverage Δ
store/models.py 82.92% <ø> (ø)
cart/cart.py 86.20% <86.95%> (+54.83%) ⬆️
shipping/calculator.py 15.38% <100.00%> (ø)

... and 4 files with indirect coverage changes

☔ View full report in Codecov by Sentry.
📢 Do you have feedback about the report comment? Let us know in this issue.

@brylie brylie merged commit 413cd19 into WesternFriend:main Jun 16, 2023
@brylie
Copy link
Member

brylie commented Jun 16, 2023

@all-contributors please add @josh-bristow for code, test

@allcontributors
Copy link
Contributor

@brylie

I've put up a pull request to add @josh-bristow! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

improve test coverage for cart app
2 participants