Skip to content

Commit 3840e3a

Browse files
committed
update pytest warning factory boy
1 parent ae1a4b0 commit 3840e3a

File tree

3 files changed

+48
-2
lines changed

3 files changed

+48
-2
lines changed

products/views.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,13 @@ def get_permissions(self):
1717

1818
def get_queryset(self):
1919
user = self.request.user
20-
if user.role == 'ADMIN':
20+
21+
if user.role == "ADMIN":
2122
return Product.objects.all()
23+
24+
if user.role == "STAFF":
25+
return Product.objects.filter(is_public=True)
26+
2227
return Product.objects.filter(owner=user)
2328

2429
def perform_create(self, serializer):

tests/factories.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,19 @@
88
class UserFactory(factory.django.DjangoModelFactory):
99
class Meta:
1010
model = User
11+
skip_postgeneration_save = True # ✅ ESTA LÍNEA ELIMINA EL WARNING
1112

1213
username = factory.Sequence(lambda n: f"user{n}")
1314
email = factory.LazyAttribute(lambda o: f"{o.username}@test.com")
14-
password = factory.PostGenerationMethodCall('set_password', '123456')
1515
role = 'CLIENTE'
1616

17+
@factory.post_generation
18+
def password(self, create, extracted, **kwargs):
19+
pwd = extracted if extracted else "123456"
20+
self.set_password(pwd)
21+
if create:
22+
self.save()
23+
1724

1825
class AdminFactory(UserFactory):
1926
role = 'ADMIN'

tests/test_products.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,37 @@ def test_admin_can_delete_product(api_client, admin_user, get_token):
6262
response = api_client.delete(f"/api/products/{product.id}/")
6363

6464
assert response.status_code == 204
65+
66+
@pytest.mark.django_db
67+
def test_client_sees_only_own_products(api_client, client_user, get_token):
68+
ProductFactory.create_batch(3, owner=client_user)
69+
ProductFactory.create_batch(2)
70+
71+
token = get_token(client_user)
72+
api_client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
73+
74+
response = api_client.get("/api/products/")
75+
assert len(response.data) == 3
76+
77+
78+
@pytest.mark.django_db
79+
def test_staff_sees_only_public_products(api_client, staff_user, get_token):
80+
ProductFactory.create_batch(2, is_public=True)
81+
ProductFactory.create_batch(2, is_public=False)
82+
83+
token = get_token(staff_user)
84+
api_client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
85+
86+
response = api_client.get("/api/products/")
87+
assert len(response.data) == 2
88+
89+
90+
@pytest.mark.django_db
91+
def test_admin_sees_all_products(api_client, admin_user, get_token):
92+
ProductFactory.create_batch(5)
93+
94+
token = get_token(admin_user)
95+
api_client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
96+
97+
response = api_client.get("/api/products/")
98+
assert len(response.data) == 5

0 commit comments

Comments
 (0)