def test_get_user_reported_offers(self, client): user = UserFactory() offers = OfferFactory.create_batch(3) reports = [ OfferReportFactory(user=user, offer=offers[0]), OfferReportFactory(user=user, offer=offers[1]), ] # offers reported by this user should not be returned another_user = UserFactory() OfferReportFactory(user=another_user, offer=offers[2]) client.with_token(user.email) response = client.get("/native/v1/offers/reports") assert response.status_code == 200 response_reports = sorted(response.json["reportedOffers"], key=lambda x: x["offerId"]) assert response_reports == [ { "offerId": reports[0].offerId, "reportedAt": reports[0].reportedAt.isoformat(), "reason": reports[0].reason.value, }, { "offerId": reports[1].offerId, "reportedAt": reports[1].reportedAt.isoformat(), "reason": reports[1].reason.value, }, ]
def test_tag_user_had_completed_id_check(): # given recieved_beneficiary = UserFactory(hasCompletedIdCheck=False) already_beneficiary = BeneficiaryGrant18Factory(hasCompletedIdCheck=True) initiated_beneficiary = UserFactory(hasCompletedIdCheck=False) get_all_application_ids = Mock(return_value=[123, 456, 789]) get_details = Mock() get_details.side_effect = [ make_new_beneficiary_application_details(123, "received"), make_new_beneficiary_application_details(456, "received"), make_new_beneficiary_application_details(789, "initiated"), ] already_existing_user = Mock() already_existing_user.side_effect = [recieved_beneficiary, already_beneficiary, initiated_beneficiary] # when remote_tag_has_completed.run( ONE_WEEK_AGO, procedure_id=6712558, get_all_applications_ids=get_all_application_ids, get_details=get_details, already_existing_user=already_existing_user, ) assert User.query.filter(User.hasCompletedIdCheck.is_(True)).count() == 3
def test_id_piece_number_by_pass( mocked_get_content, app, ): # Given ID_PIECE_NUMBER = "NOT_APPLICABLE" subscribing_user = UserFactory( isBeneficiary=False, dateOfBirth=AGE18_ELIGIBLE_BIRTH_DATE, email=BASE_JOUVE_CONTENT["email"], ) UserFactory(idPieceNumber=ID_PIECE_NUMBER) UserFactory(idPieceNumber=None) mocked_get_content.return_value = BASE_JOUVE_CONTENT | {"bodyPieceNumber": ID_PIECE_NUMBER} # When create_beneficiary_from_application.execute(BASE_APPLICATION_ID, ignore_id_piece_number_field=True) # Then beneficiary_import = BeneficiaryImport.query.filter(BeneficiaryImport.beneficiary == subscribing_user).first() assert beneficiary_import.currentStatus == ImportStatus.CREATED assert subscribing_user.has_beneficiary_role assert not subscribing_user.idPieceNumber assert len(mails_testing.outbox) == 1
def test_run_sendinblue_only(mock_import_contacts): """ Test that two chunks of users are used and therefore two requests are sent. """ UserFactory.create_batch(5) run(4, synchronize_batch=False) assert len(mock_import_contacts.call_args_list) == 2
def test_run_batch_only(): """ Test that two chunks of users are used and therefore two requests are sent. """ UserFactory.create_batch(5) run(4, synchronize_sendinblue=False) assert len(push_testing.requests) == 2
def test_run(mock_import_contacts): """ Test that two chunks of users are used and therefore two requests are sent. """ UserFactory.create_batch(5) run(4) assert len(push_testing.requests) == 2 assert len(mock_import_contacts.call_args_list) == 2
def when_user_is_a_pro(self, app): # Given user = UserFactory(email="*****@*****.**", postalCode=None, isBeneficiary=False, dateOfBirth=None) user.suspensionReason = None repository.save(user) # When response = TestClient(app.test_client()).with_auth("*****@*****.**").get("/beneficiaries/current") # Then assert response.status_code == 200 assert response.json["suspensionReason"] == None
def test_should_return_thing_data_when_booking_is_a_thing( self, mock_format_environment_for_email): # Given booking = factories.BookingFactory( user=UserFactory(email="*****@*****.**", firstName="Fabien"), isCancelled=True, stock=ThingStockFactory( price=10.2, beginningDatetime=datetime.now() - timedelta(days=1), offer__name="Test thing name", offer__id=123456, ), ) # When email_data = make_beneficiary_booking_cancellation_email_data(booking) # Then assert email_data == { "FromEmail": "*****@*****.**", "Mj-TemplateID": 1091464, "Mj-TemplateLanguage": True, "To": "*****@*****.**", "Vars": { "env": "", "event_date": "", "event_hour": "", "is_event": 0, "is_free_offer": 0, "offer_id": "AHREA", "offer_name": "Test thing name", "offer_price": "10.20", "user_first_name": "Fabien", }, }
def test_get_reasons(self, app, client): user = UserFactory() response = client.with_token( user.email).get("/native/v1/offer/report/reasons") assert response.status_code == 200 assert response.json["reasons"] == { "IMPROPER": { "title": "La description est non conforme", "description": "La date ne correspond pas, mauvaise description...", }, "PRICE_TOO_HIGH": { "title": "Le tarif est trop élevé", "description": "comparé à l'offre publique" }, "INAPPROPRIATE": { "title": "Le contenu est inapproprié", "description": "violence, incitation à la haine, nudité...", }, "OTHER": { "title": "Autre", "description": "" }, }
def test_id_piece_number_no_duplicate( mocked_get_content, app, ): # Given ID_PIECE_NUMBER = "140767100016" subscribing_user = UserFactory( isBeneficiary=False, dateOfBirth=AGE18_ELIGIBLE_BIRTH_DATE, email=BASE_JOUVE_CONTENT["email"], idPieceNumber=None, ) mocked_get_content.return_value = BASE_JOUVE_CONTENT | {"bodyPieceNumber": ID_PIECE_NUMBER} # When create_beneficiary_from_application.execute(BASE_APPLICATION_ID) # Then beneficiary_import = BeneficiaryImport.query.filter(BeneficiaryImport.beneficiary == subscribing_user).first() assert beneficiary_import.currentStatus == ImportStatus.CREATED assert len(mails_testing.outbox) == 1 assert mails_testing.outbox[0].sent_data["Mj-TemplateID"] == 2016025 db.session.refresh(subscribing_user) assert subscribing_user.idPieceNumber == ID_PIECE_NUMBER
def test_venue_does_not_exist(app): user = UserFactory() client = TestClient(app.test_client()).with_session_auth(email=user.email) response = client.get("/providers/AZER") assert response.status_code == 404
def test_should_return_event_data_when_booking_is_an_event(self): # Given booking = factories.BookingFactory( user=UserFactory(email="*****@*****.**", firstName="Fabien"), isCancelled=True, stock=EventStockFactory( price=10.2, beginningDatetime=datetime.utcnow(), offer__name="Test event name", offer__id=123456, ), ) # When email_data = make_beneficiary_booking_cancellation_email_data(booking) # Then assert email_data == { "Mj-TemplateID": 1091464, "Mj-TemplateLanguage": True, "Vars": { "can_book_again": 1, "event_date": "26 novembre", "event_hour": "19h29", "is_event": 1, "is_free_offer": 0, "offer_id": "AHREA", "offer_name": "Test event name", "offer_price": "10.20", "user_first_name": "Fabien", }, }
def test_wrong_format(self, mock_get_distant_image, caplog, app): # Given caplog.set_level(logging.INFO) body = {"url": "https://example.com/meme.gif"} user = UserFactory() auth_request = TestClient(app.test_client()).with_auth(email=user.email) mock_get_distant_image.side_effect = exceptions.UnacceptedFileType( accepted_types=( "png", "jpg", "jpeg", ) ) # When response = auth_request.post( "/offers/thumbnail-url-validation", json=body, headers={"origin": "http://localhost:3000"} ) # Then assert response.status_code == 200 assert ( caplog.records[0].message == "When validating image at: https://example.com/meme.gif, this error was encountered: UnacceptedFileType" ) assert response.json == {"errors": ["Utilisez un format png, jpg, jpeg"], "image": None}
def when_user_has_booked_some_offers(self, app): # Given user = UserFactory( email="*****@*****.**", postalCode="93020", ) offerer = create_offerer( siren="999199987", address="2 Test adress", city="Test city", postal_code="93000", name="Test offerer" ) venue = create_venue(offerer) thing_offer = create_offer_with_thing_product(venue=None) stock = create_stock_with_thing_offer(offerer, venue, thing_offer, price=5) booking = create_booking(user=user, stock=stock, venue=venue, quantity=1) repository.save(venue, booking) # When response = TestClient(app.test_client()).with_auth("*****@*****.**").get("/beneficiaries/current") # Then assert response.json["wallet_balance"] == 495.0 assert response.json["expenses"] == [ {"domain": "all", "current": 5.0, "limit": 500.0}, {"domain": "digital", "current": 0.0, "limit": 200.0}, {"domain": "physical", "current": 5.0, "limit": 200.0}, ]
def test_venue_has_known_allocine_id(app): # Given user = UserFactory() venue = VenueFactory(siret="12345678912345") AllocinePivotFactory(siret="12345678912345") allocine_provider = ProviderFactory(localClass="AllocineStocks") other_provider = ProviderFactory(localClass="B provider") # When client = TestClient(app.test_client()).with_session_auth(email=user.email) response = client.get(f"/providers/{humanize(venue.id)}") # Then assert response.status_code == 200 returned_providers = sorted(response.json, key=lambda d: d["localClass"]) assert len(returned_providers) == 5 assert returned_providers[:2] == [ { "enabledForPro": True, "id": humanize(allocine_provider.id), "isActive": True, "localClass": "AllocineStocks", "name": "Allociné", }, { "enabledForPro": True, "id": humanize(other_provider.id), "isActive": True, "localClass": other_provider.localClass, "name": other_provider.name, }, ]
def test_send_phone_validation_and_become_beneficiary(app): """ Test that a user with a CREATED import becomes a beneficiary once its phone number is vaidated. """ AGE18_ELIGIBLE_BIRTH_DATE = datetime.now() - relativedelta(years=18, months=4) user = UserFactory( dateOfBirth=AGE18_ELIGIBLE_BIRTH_DATE, isEmailValidated=True, phoneNumber="+33601020304", hasCompletedIdCheck=True, ) beneficiary_import = BeneficiaryImportFactory(beneficiary=user) beneficiary_import.setStatus(ImportStatus.CREATED) client = TestClient(app.test_client()).with_session_auth(email=user.email) response = client.post("/send_phone_validation_code") assert response.status_code == 204 assert len(sms_testing.requests) == 1 token = Token.query.filter_by(userId=user.id, type="PHONE_VALIDATION").first() response = client.post("/validate_phone_number", {"code": token.value}) assert response.status_code == 204 user = User.query.get(user.id) assert user.is_phone_validated assert user.has_beneficiary_role
def test_when_no_deposit(self): # given user = UserFactory() repository.delete(*user.deposits) # then assert user.deposit_version == None
def when_changes_are_allowed(self, app): # given user = UserFactory() user_id = user.id data = { "publicName": "Anne", "email": "*****@*****.**", "postalCode": "93020", "phoneNumber": "1234567890", "departementCode": "97", "hasSeenTutorials": True, } # when response = (TestClient(app.test_client()).with_auth( email=user.email).patch("/beneficiaries/current", json=data)) # then user = User.query.get(user_id) assert response.status_code == 200 assert response.json["id"] == humanize(user.id) assert response.json["publicName"] == user.publicName assert user.publicName == data["publicName"] assert response.json["email"] == user.email assert user.email == data["email"] assert response.json["postalCode"] == user.postalCode assert user.postalCode == data["postalCode"] assert response.json["phoneNumber"] == user.phoneNumber assert user.phoneNumber == data["phoneNumber"] assert response.json["departementCode"] == user.departementCode assert user.departementCode == data["departementCode"]
def test_send_phone_validation(app): """ Test phone code validation. + ensure that a user that has no import operation does not become beneficiary. """ user = UserFactory(isEmailValidated=True, phoneNumber="+33601020304") client = TestClient(app.test_client()).with_session_auth(email=user.email) response = client.post("/send_phone_validation_code") assert response.status_code == 204 assert len(sms_testing.requests) == 1 token = Token.query.filter_by(userId=user.id, type="PHONE_VALIDATION").first() response = client.post("/validate_phone_number", {"code": token.value}) assert response.status_code == 204 user = User.query.get(user.id) assert user.is_phone_validated assert not user.has_beneficiary_role
def test_only_suspend_beneficiary_users_in_given_emails_providers_list( self): # Given fraudulent_emails_providers = ["example.com"] admin_user = AdminFactory() beneficiary_fraudulent_user = BeneficiaryGrant18Factory( email="*****@*****.**") beneficiary_fraudulent_user_with_uppercase_domain = BeneficiaryGrant18Factory( email="*****@*****.**") beneficiary_fraudulent_user_with_subdomain = BeneficiaryGrant18Factory( email="*****@*****.**") non_beneficiary_fraudulent_user = UserFactory( email="*****@*****.**") booking_factories.IndividualBookingFactory( individualBooking__user=beneficiary_fraudulent_user, stock__price=1) # When suspend_fraudulent_beneficiary_users_by_email_providers( fraudulent_emails_providers, admin_user, dry_run=False) # Then assert not beneficiary_fraudulent_user.isActive assert not beneficiary_fraudulent_user_with_uppercase_domain.isActive # Do not handle sub-domains assert beneficiary_fraudulent_user_with_subdomain.isActive assert non_beneficiary_fraudulent_user.isActive
def test_unaccessible_file(self, mock_get_distant_image, caplog, app): # Given caplog.set_level(logging.INFO) body = {"url": "https://example.com/bla"} user = UserFactory() auth_request = TestClient(app.test_client()).with_auth(email=user.email) mock_get_distant_image.side_effect = exceptions.FailureToRetrieve() # When response = auth_request.post( "/offers/thumbnail-url-validation", json=body, headers={"origin": "http://localhost:3000"} ) # Then assert response.status_code == 200 assert ( caplog.records[0].message == "When validating image at: https://example.com/bla, this error was encountered: FailureToRetrieve" ) assert response.json == { "errors": [ "Nous n’avons pas pu récupérer cette image; vous pouvez la télécharger " 'puis l’importer depuis l’onglet "Importer"' ], "image": None, }
def test_venue_has_no_allocine_id(app): # Given user = UserFactory(email="*****@*****.**") venue = VenueFactory() allocine_provider = ProviderFactory(localClass="AllocineStocks") other_provider = ProviderFactory(localClass="B provider") # When client = TestClient(app.test_client()).with_session_auth(email=user.email) response = client.get(f"/providers/{humanize(venue.id)}") # Then assert response.status_code == 200 returned_providers = sorted(response.json, key=lambda d: d["localClass"]) assert len(returned_providers) == 4 assert returned_providers[0] == { "enabledForPro": True, "id": humanize(other_provider.id), "isActive": True, "localClass": other_provider.localClass, "name": other_provider.name, } assert humanize( allocine_provider.id) not in [p["id"] for p in returned_providers]
def test_synchronize_unsubscribed_users(self, _get_emails, format_sendinblue_users, import_contacts_in_sendinblue): default_notification_subscriptions_value = {"marketing_push": True, "marketing_email": True} updated_notification_subscriptions_value = {"marketing_push": True, "marketing_email": False} user_nominal = UserFactory(notificationSubscriptions=default_notification_subscriptions_value) user_control = UserFactory(notificationSubscriptions=default_notification_subscriptions_value) user_null_value = UserFactory() user_null_value.notificationSubscriptions = None user_empty_value = UserFactory(notificationSubscriptions={}) user_somewhat_empty_value = UserFactory(notificationSubscriptions={"marketing_push": True}) users_to_import = [ user_nominal.email, user_null_value.email, user_empty_value.email, user_somewhat_empty_value.email, "*****@*****.**", ] _get_emails.return_value = users_to_import synchronize_unsubscribed_users() assert user_control.notificationSubscriptions == default_notification_subscriptions_value assert user_nominal.notificationSubscriptions == updated_notification_subscriptions_value assert user_null_value.notificationSubscriptions == {"marketing_email": False} assert user_empty_value.notificationSubscriptions == {"marketing_email": False} assert user_somewhat_empty_value.notificationSubscriptions == updated_notification_subscriptions_value format_sendinblue_users.assert_called_once() import_contacts_in_sendinblue.assert_called_once()
def when_user_is_a_admin(self, app): # Given UserFactory(email="*****@*****.**", postalCode=None, dateOfBirth=None, isAdmin=True) # When response = TestClient(app.test_client()).with_auth("*****@*****.**").get("/beneficiaries/current") # Then assert response.status_code == 200
def test_id_piece_number_wrong_format(mocked_get_content, id_piece_number): subscribing_user = UserFactory( isBeneficiary=False, dateOfBirth=AGE18_ELIGIBLE_BIRTH_DATE, email=BASE_JOUVE_CONTENT["email"], ) UserFactory(idPieceNumber=id_piece_number) mocked_get_content.return_value = BASE_JOUVE_CONTENT | {"bodyPieceNumber": id_piece_number} # When create_beneficiary_from_application.execute(BASE_APPLICATION_ID) # Then assert len(subscribing_user.beneficiaryImports) == 0 assert len(mails_testing.outbox) == 1 assert mails_testing.outbox[0].sent_data["Mj-TemplateID"] == 2905960 assert mails_testing.outbox[0].sent_data["Mj-campaign"] == "dossier-en-analyse"
def when_user_is_created_without_postal_code(self, app): # Given UserFactory(email="*****@*****.**", postalCode=None) # When response = TestClient(app.test_client()).with_auth("*****@*****.**").get("/beneficiaries/current") # Then assert response.status_code == 200
def test_get_no_reported_offers(self, client): user = UserFactory() OfferFactory() client.with_token(user.email) response = client.get("/native/v1/offers/reports") assert response.status_code == 200 assert not response.json["reportedOffers"]
def should_humanize_the_user_id(self, app): # Given beneficiary = UserFactory(id=1) # When response = BeneficiaryAccountResponse.from_orm(beneficiary) # Then assert response.id == "AE"
def should_return_bookings_by_beneficiary_id(self, app): # Given user1 = UserFactory() user2 = UserFactory() offerer = create_offerer() venue = create_venue(offerer) offer = create_offer_with_event_product(venue) stock = create_stock(offer=offer) booking1 = create_booking(user=user1, stock=stock) booking2 = create_booking(user=user2, stock=stock) repository.save(booking1, booking2) # When result = BeneficiaryBookingsSQLRepository().get_beneficiary_bookings(beneficiary_id=user1.id) # Then assert len(result.bookings) == 1 assert result.bookings[0].id == booking1.id
def should_return_deposit_version(self, app): # Given UserFactory(email="*****@*****.**", postalCode="93020", deposit__version=1) # When response = TestClient(app.test_client()).with_auth("*****@*****.**").get("/beneficiaries/current") # Then assert response.json["deposit_version"] == 1