Skip to content

Commit

Permalink
(BSR)[API] test: misc pylint errors in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
cnormant-pass committed Jan 29, 2025
1 parent 587792d commit 25dafa9
Show file tree
Hide file tree
Showing 16 changed files with 43 additions and 27 deletions.
2 changes: 1 addition & 1 deletion api/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -850,7 +850,7 @@ def db_session(_engine, _transaction, mocker, request):

# No need for the fixture, `clean_database` will do the job
if "clean_database" in request.fixturenames:
return
return None

_, _, _session = _transaction

Expand Down
2 changes: 1 addition & 1 deletion api/tests/core/achievements/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pcapi.core.achievements import api as achievements_api
from pcapi.core.achievements import models as achievements_models
from pcapi.core.bookings import factories as bookings_factories
from pcapi.core.categories import subcategories_v2 as subcategories_v2
from pcapi.core.categories import subcategories_v2
from pcapi.core.users import factories as users_factories


Expand Down
2 changes: 1 addition & 1 deletion api/tests/core/bookings/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def test_if_it_is_first_venue_booking_to_send_specific_email(self):
assert email_data1["template"] == dataclasses.asdict(
TransactionalEmail.FIRST_VENUE_BOOKING_TO_PRO.value
) # to offerer
email_data1["params"]["OFFER_ADDRESS"] == stock.offer.fullAddress
assert email_data1["params"]["OFFER_ADDRESS"] == stock.offer.fullAddress
email_data2 = mails_testing.outbox[1]
assert email_data2["template"] == dataclasses.asdict(
TransactionalEmail.BOOKING_CONFIRMATION_BY_BENEFICIARY.value
Expand Down
2 changes: 1 addition & 1 deletion api/tests/core/bookings/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import pytz
import time_machine

import pcapi.core.bookings.utils as utils
from pcapi.core.bookings import utils
from pcapi.core.categories import subcategories_v2 as subcategories


Expand Down
2 changes: 1 addition & 1 deletion api/tests/core/external/pro_user_automations_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def test_automation(self):
mock_run_query.return_value = mocked_bq_rows()

with patch(self.MOCK_IMPORT_CONTACT_PATH) as mock_import_contacts:
assert type(self).func()
assert type(self).func() # pylint: disable=no-value-for-parameter # I don't get this code

expected_params = build_expected_called_params(self.id)
mock_import_contacts.assert_called_once_with(expected_params)
Expand Down
23 changes: 14 additions & 9 deletions api/tests/core/external_bookings/test_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,19 @@
from unittest.mock import Mock

import pytest
from requests.exceptions import ReadTimeout
from requests.exceptions import Timeout

from pcapi.core.bookings import models as bookings_models
from pcapi.core.external_bookings import models as external_bookings_models
from pcapi.core.external_bookings.decorators import ExternalBookingDecoratorException
from pcapi.core.external_bookings.decorators import catch_cinema_provider_request_timeout
from pcapi.core.external_bookings.exceptions import ExternalBookingTimeoutException
from pcapi.core.users import models as users_models
from pcapi.utils.requests import requests


class FakeExternalBookingClientAPI(external_bookings_models.ExternalBookingsClientAPI):
def __init__(self, cinema_id: str, connector) -> None:
self.cinema_id = cinema_id
super().__init__(cinema_id)
self.connector = connector

@catch_cinema_provider_request_timeout
Expand All @@ -26,6 +25,12 @@ def get_film_showtimes_stocks(self, film_id):
def book_ticket(self, show_id, booking, beneficiary):
return self.connector.make_request(show_id, booking, beneficiary)

def cancel_booking(self, barcodes):
pass

def get_shows_remaining_places(self, shows_id):
return {}


class FakeClass:
@catch_cinema_provider_request_timeout
Expand All @@ -52,14 +57,15 @@ def test_should_raise_understandable_error_if_the_decorated_func_is_called_with_
client = FakeExternalBookingClientAPI(cinema_id=1, connector=Mock())

with pytest.raises(TypeError) as exception:
client.get_film_showtimes_stocks(12, show_id=1)
# We ignore the pylint error because we test incorrect args here
client.get_film_showtimes_stocks(12, show_id=1) # pylint: disable=unexpected-keyword-arg
assert (
str(exception.value)
== "TypeError: get_film_showtimes_stocks() got an unexpected keyword argument 'show_id'"
)

with pytest.raises(TypeError) as exception:
client.get_film_showtimes_stocks(12, 13, 24)
client.get_film_showtimes_stocks(12, 13, 24) # pylint: disable=too-many-function-args
assert (
str(exception.value)
== "TypeError: get_film_showtimes_stocks() takes 1 positional arguments but 3 were given"
Expand All @@ -71,7 +77,7 @@ def test_should_raise_understandable_error_if_the_decorated_func_is_called_with_
(
[12345],
{"booking": bookings_models.Booking(id=1), "beneficiary": users_models.User(id=3)},
ReadTimeout,
requests.exceptions.ReadTimeout,
Mock(url="https://provider.com/route/un/peu/instable", method="POST"),
{
"cinema_id": 789,
Expand All @@ -88,7 +94,7 @@ def test_should_raise_understandable_error_if_the_decorated_func_is_called_with_
(
[678, bookings_models.Booking(id=1), users_models.User(id=3)],
{},
Timeout,
requests.exceptions.Timeout,
Mock(url="https://provider.com/route/qui/timeout", method="GET"),
{
"cinema_id": 789,
Expand All @@ -109,13 +115,12 @@ def test_should_raise_understandable_error_if_the_decorated_func_is_called_with_
"booking": bookings_models.Booking(id=4567),
"beneficiary": users_models.User(id=12345767),
},
ReadTimeout,
requests.exceptions.ReadTimeout,
Mock(url="https://provider.com/oh/zut/encore/un/timeout", method="PUT"),
{
"cinema_id": 789,
"method": "book_ticket",
"client": "FakeExternalBookingClientAPI",
"cinema_id": 789,
"method_params": {
"show_id": "562",
"booking": "<Booking #4567>",
Expand Down
2 changes: 1 addition & 1 deletion api/tests/core/offerers/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1899,7 +1899,7 @@ def test_get_offerer_stats_dashboard_url():

class GetOffererTotalRevenueTest:
def _create_data(self):
today = datetime.datetime.now(datetime.timezone.utc)
today = datetime.datetime.now(datetime.timezone.utc) # pylint: disable=datetime-now
offerer = offerers_factories.OffererFactory()
bookings_factories.BookingFactory(stock__offer__venue__managingOfferer=offerer, stock__price=10)
bookings_factories.UsedBookingFactory(
Expand Down
8 changes: 6 additions & 2 deletions api/tests/core/offers/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -847,8 +847,12 @@ def test_check_booking_limit_datetime_priorisation_order(self, time_zone_expecte
beginning_date = datetime.datetime(2024, 7, 19, 8, tzinfo=datetime.timezone.utc)
booking_limit_date = beginning_date - datetime.timedelta(hours=1)

beginning, booking_limit_datetime = validation.check_booking_limit_datetime(
stock, beginning=beginning_date, booking_limit_datetime=booking_limit_date
# It's ok to ignore the tuple unpacking warning here because we are testing the value of beginning
# and it should fails if check_booking_limit_datetime returns an empty list
beginning, booking_limit_datetime = ( # pylint: disable=unbalanced-tuple-unpacking
validation.check_booking_limit_datetime(
stock, beginning=beginning_date, booking_limit_datetime=booking_limit_date
)
)
assert beginning.tzinfo == booking_limit_datetime.tzinfo == time_zone_expected

Expand Down
3 changes: 2 additions & 1 deletion api/tests/routes/backoffice/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,8 @@ def collective_offerer_booking_fixture(venue_with_educational_status):

@pytest.fixture(name="today", scope="module")
def today_fixture():
return datetime.datetime.now(datetime.timezone.utc)
# Disable datetime-now custom rule, here we use the timezone aware datetime at UTC
return datetime.datetime.now(datetime.timezone.utc) # pylint: disable=datetime-now


@pytest.fixture(name="collective_venue_booking")
Expand Down
4 changes: 2 additions & 2 deletions api/tests/routes/native/v1/bookings_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def test_bookings_with_external_event_booking_infos(self, client, requests_mock)
== hmac.new(provider.hmacKey.encode(), json.dumps(json_data).encode(), hashlib.sha256).hexdigest()
)

now = datetime.now()
now = datetime.utcnow()
json_confirmation_date = datetime.fromisoformat(json_data.pop("booking_confirmation_date"))
json_creation_date = datetime.fromisoformat(json_data.pop("booking_creation_date"))

Expand Down Expand Up @@ -362,7 +362,7 @@ def test_bookings_with_external_event_booking_and_remaining_quantity_unlimited(s
assert response.status_code == 200
json_data = json.loads(requests_mock.last_request.json())

now = datetime.now()
now = datetime.utcnow()
json_confirmation_date = datetime.fromisoformat(json_data.pop("booking_confirmation_date"))
json_creation_date = datetime.fromisoformat(json_data.pop("booking_creation_date"))

Expand Down
5 changes: 4 additions & 1 deletion api/tests/routes/pro/get_offerer_addresses_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,12 +169,15 @@ def test_get_offerer_addresses_is_editable(self, client, linked_to_venue):

if linked_to_venue:
venue = offerers_factories.VenueFactory(managingOfferer=offerer, offererAddress=offerer_address_1)
venue_public_name = venue.common_name
else:
venue_public_name = None

client = client.with_session_auth(email=pro.email)
offerer_id = offerer.id
offerer_address_1_id = offerer_address_1.id
offerer_address_2_id = offerer_address_2.id
offerer_address_3_id = offerer_address_3.id
venue_public_name = venue.common_name if linked_to_venue else None
with assert_num_queries(self.num_queries):
response = client.get(f"/offerers/{offerer_id}/offerer_addresses")
assert response.status_code == 200
Expand Down
2 changes: 1 addition & 1 deletion api/tests/routes/pro/get_statistics_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ def test_get_statistics_with_no_venue_id_should_fail(self, client):
test_client = client.with_session_auth(email=user.email)
num_queries = testing.AUTHENTICATION_QUERIES
with testing.assert_num_queries(num_queries):
response = test_client.get(f"/get-statistics/")
response = test_client.get("/get-statistics/")
assert response.status_code == 422
assert response.json["global"] == ["Vous devez préciser au moins un ID de partenaire culturel"]

Expand Down
4 changes: 2 additions & 2 deletions api/tests/routes/pro/patch_draft_offer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ def test_first_step_funnel_creation_shouldnt_create_offer_offerer_address_ff_off
},
}
user_email = user_offerer.user.email
response = client.with_session_auth(user_email).post(f"/offers/draft", json=data)
response = client.with_session_auth(user_email).post("/offers/draft", json=data)
assert response.status_code == 201

draft_offer = Offer.query.one()
Expand Down Expand Up @@ -546,7 +546,7 @@ def test_first_step_funnel_creation_shouldnt_create_offer_offerer_address_ff_on(
},
}
user_email = user_offerer.user.email
response = client.with_session_auth(user_email).post(f"/offers/draft", json=data)
response = client.with_session_auth(user_email).post("/offers/draft", json=data)
assert response.status_code == 201

draft_offer = Offer.query.one()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -695,7 +695,10 @@ def test_cannot_book_offer_if_no_educational_year_matches_start(self, client):
# deposit creates an educational year
collectiveOffer__institution=deposit.educationalInstitution,
# start will not match the educational year
startDatetime=datetime.now(timezone.utc) + timedelta(weeks=512),
startDatetime=datetime.now( # pylint: disable=datetime-now # ok because we use timezone aware datetime
timezone.utc
)
+ timedelta(weeks=512),
).collectiveOffer

self.assert_request_has_expected_result(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,5 +202,5 @@ def test_should_raise_400_because_municipality_not_found_on_BAN_API(

assert result.status_code == 400
assert result.json == {
"__root__": [f"No municipality found for `city=Parisse (comme disent les Anglais)` and `postalCode=75017`"]
"__root__": ["No municipality found for `city=Parisse (comme disent les Anglais)` and `postalCode=75017`"]
}
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ def test_should_raise_400_because_municipality_not_found_on_BAN_API(

assert result.status_code == 400
assert result.json == {
"__root__": [f"No municipality found for `city=Parisse (comme disent les Anglais)` and `postalCode=75017`"]
"__root__": ["No municipality found for `city=Parisse (comme disent les Anglais)` and `postalCode=75017`"]
}

@patch("pcapi.connectors.api_adresse.get_municipality_centroid")
Expand Down

0 comments on commit 25dafa9

Please sign in to comment.