Ejemplo n.º 1
0
    def test_command(self, mock_datetime, mock_logger, mock_send_mail):
        mock_datetime.now.return_value = datetime(2020, 7, 27, 0, 0, 0)
        mock_send_mail.side_effect = [None, AnymailError('Connection error')]

        call_command('detect_inactive_privileged_users')

        self.assertFalse(
            User.objects.get(email='*****@*****.**').is_active)
        self.assertTrue(
            User.objects.get(email='*****@*****.**').is_active)

        mock_send_mail.assert_has_calls([
            mock.call('Warning: seqr account deactivation', WARNING_EMAIL,
                      None, ['*****@*****.**']),
            mock.call('Warning: seqr account deactivated', DEACTIVATED_EMAIL,
                      None, ['*****@*****.**']),
        ])

        mock_logger.error.assert_called_with(
            'Unable to send email: Connection error')
        mock_logger.info.assert_has_calls([
            mock.call('Checking for inactive users'),
            mock.call(
                'Warning [email protected] of impending account inactivation'
            ),
            mock.call('Inactivating account for [email protected]'),
            mock.call('Inactive user check complete'),
        ])
Ejemplo n.º 2
0
    def test_create_staff_user(self, mock_send_mail):
        create_url = reverse(create_staff_user)
        self.check_staff_login(create_url)

        # send invalid request
        response = self.client.post(create_url,
                                    content_type='application/json',
                                    data=json.dumps({}))
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.reason_phrase, 'Email is required')

        # create
        response = self.client.post(create_url,
                                    content_type='application/json',
                                    data=json.dumps({
                                        'email': '*****@*****.**',
                                        'firstName': 'Test',
                                        'lastName': 'Staff'
                                    }))
        self.assertEqual(response.status_code, 200)
        user = User.objects.get(email='*****@*****.**')
        self.assertTrue(user.is_staff)

        expected_email_content = """
    Hi there Test Staff--

    Test User has added you as a collaborator in seqr.

    Please click this link to set up your account:
    /users/set_password/{password_token}

    Thanks!
    """.format(password_token=user.password)
        mock_send_mail.assert_called_with(
            'Set up your seqr account',
            expected_email_content,
            None,
            ['*****@*****.**'],
            fail_silently=False,
        )

        # calling create again fails
        response = self.client.post(create_url,
                                    content_type='application/json',
                                    data=json.dumps(
                                        {'email': '*****@*****.**'}))
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.reason_phrase, 'This user already exists')

        # Test email failure
        mock_send_mail.side_effect = AnymailError('Connection err')
        response = self.client.post(create_url,
                                    content_type='application/json',
                                    data=json.dumps(
                                        {'email': '*****@*****.**'}))
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.reason_phrase, 'Connection err')
Ejemplo n.º 3
0
    def test_forgot_password(self, mock_send_mail):
        url = reverse(forgot_password)

        # send invalid requests
        response = self.client.post(url,
                                    content_type='application/json',
                                    data=json.dumps({}))
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.reason_phrase, 'Email is required')

        response = self.client.post(url,
                                    content_type='application/json',
                                    data=json.dumps(
                                        {'email': '*****@*****.**'}))
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.reason_phrase,
                         'No account found for this email')

        # Send valid request
        response = self.client.post(url,
                                    content_type='application/json',
                                    data=json.dumps(
                                        {'email': '*****@*****.**'}))
        self.assertEqual(response.status_code, 200)

        expected_email_content = """
        Hi there Test User--

        Please click this link to reset your seqr password:
        /users/set_password/pbkdf2_sha256%2430000%24y85kZgvhQ539%24jrEC3L1IhCezUx3Itp%2B14w%2FT7U6u5XUxtpBZXKv8eh4%3D?reset=true
        """
        mock_send_mail.assert_called_with(
            'Reset your seqr password',
            expected_email_content,
            None,
            ['*****@*****.**'],
            fail_silently=False,
        )

        # Test email failure
        mock_send_mail.side_effect = AnymailError('Connection err')
        response = self.client.post(url,
                                    content_type='application/json',
                                    data=json.dumps(
                                        {'email': '*****@*****.**'}))
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.reason_phrase, 'Connection err')
Ejemplo n.º 4
0
def test_approve_order_anymail_error(
    superuser_api_client,
    payment_provider,
    notification_template_orders_approved,
    order: Order,
):
    order.status = OrderStatus.DRAFTED
    order.save(update_fields=["status"])

    order_id = to_global_id(OrderNode, order.id)
    previous_order_status = order.status
    previous_lease_status = order.lease.status
    previous_application_status = order.lease.application.status

    variables = {
        "orders": [{
            "orderId": order_id,
            "email": "*****@*****.**"
        }],
    }

    with patch(
            "customers.services.profile.requests.post",
            side_effect=mocked_response_profile(count=1,
                                                data=None,
                                                use_edges=False),
    ):
        with patch(
                "payments.utils.send_notification",
                side_effect=AnymailError("Anymail error"),
        ) as mock:
            executed = superuser_api_client.execute(APPROVE_ORDER_MUTATION,
                                                    input=variables)

    mock.assert_called_once()

    assert len(executed["data"]["approveOrders"]["failedOrders"]) == 1
    assert executed["data"]["approveOrders"]["failedOrders"][0] == {
        "id": order_id,
        "error": "Anymail error",
    }

    order = Order.objects.get(id=order.id)

    assert order.status == previous_order_status
    assert order.lease.status == previous_lease_status.value
    assert order.lease.application.status == previous_application_status
Ejemplo n.º 5
0
def test_keep_email_send_log_after_exception(
    send_task,
    buyer,
    seller,
    client,
    order,
    order_items,
    central_platform_user,
    platform_user,
    logistics_user,
):

    send_task.side_effect = [True, True, AnymailError("Boom")]
    with pytest.raises(AnymailError):
        client.post(
            reverse("task",
                    kwargs={
                        "order_id": order.id,
                        "document_set": "all"
                    }))
    assert DocumentSendLog.objects.count() == 2
Ejemplo n.º 6
0
    def test_create_project_collaborator(self, mock_send_mail, mock_logger):
        create_url = reverse(create_project_collaborator,
                             args=[NON_ANVIL_PROJECT_GUID])
        self.check_manager_login(create_url)

        # send invalid request
        response = self.client.post(create_url,
                                    content_type='application/json',
                                    data=json.dumps({}))
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json()['error'], 'Email is required')

        # create
        response = self.client.post(create_url,
                                    content_type='application/json',
                                    data=json.dumps({
                                        'email': '*****@*****.**',
                                        'firstName': 'Test'
                                    }))
        self.assertEqual(response.status_code, 200)
        collaborators = response.json(
        )['projectsByGuid'][NON_ANVIL_PROJECT_GUID]['collaborators']
        self.assertEqual(len(collaborators),
                         len(self.LOCAL_COLLABORATOR_NAMES) + 1)
        expected_fields = {'hasEditPermissions', 'hasViewPermissions'}
        expected_fields.update(USER_FIELDS)
        self.assertSetEqual(set(collaborators[0].keys()), expected_fields)
        self.assertEqual(collaborators[0]['email'], '*****@*****.**')
        self.assertEqual(collaborators[0]['displayName'], 'Test')
        self.assertFalse(collaborators[0]['isSuperuser'])
        self.assertFalse(collaborators[0]['isAnalyst'])
        self.assertFalse(collaborators[0]['isDataManager'])
        self.assertFalse(collaborators[0]['isPm'])
        self.assertTrue(collaborators[0]['hasViewPermissions'])
        self.assertFalse(collaborators[0]['hasEditPermissions'])

        username = collaborators[0]['username']
        user = User.objects.get(username=username)

        expected_email_content = """
    Hi there Test--

    Test Manager User has added you as a collaborator in seqr.

    {setup_message}

    Thanks!
    """.format(setup_message=self.EMAIL_SETUP_MESSAGE.format(
            password_token=user.password))
        mock_send_mail.assert_called_with(
            'Set up your seqr account',
            expected_email_content,
            None,
            ['*****@*****.**'],
            fail_silently=False,
        )
        mock_send_mail.reset_mock()

        mock_logger.info.assert_called_with(
            'Created user [email protected] (local)', self.manager_user)
        mock_logger.reset_mock()

        # check user object added to project set
        self.assertEqual(
            Project.objects.get(
                guid=NON_ANVIL_PROJECT_GUID).can_view_group.user_set.filter(
                    username=username).count(), 1)

        # calling create again just updates the existing user
        response = self.client.post(create_url,
                                    content_type='application/json',
                                    data=json.dumps({
                                        'email':
                                        '*****@*****.**',
                                        'firstName':
                                        'Test',
                                        'lastName':
                                        'Invalid Name Update'
                                    }))
        self.assertEqual(response.status_code, 200)
        collaborators = response.json(
        )['projectsByGuid'][NON_ANVIL_PROJECT_GUID]['collaborators']
        self.assertEqual(len(collaborators),
                         len(self.LOCAL_COLLABORATOR_NAMES) + 1)
        new_collab = next(collab for collab in collaborators
                          if collab['email'] == '*****@*****.**')
        self.assertEqual(new_collab['username'], username)
        self.assertEqual(new_collab['displayName'], 'Test')
        mock_send_mail.assert_not_called()
        mock_logger.info.assert_not_called()

        # Test email failure
        mock_send_mail.side_effect = AnymailError('Connection err')
        response = self.client.post(create_url,
                                    content_type='application/json',
                                    data=json.dumps(
                                        {'email': '*****@*****.**'}))
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json()['error'], 'Connection err')
def test_send_berth_invoices_send_error(notification_template_orders_approved):
    lease = _lease_with_contract(
        boat=None,
        status=LeaseStatus.PAID,
        start_date=today() - relativedelta(years=1),
        end_date=today() + relativedelta(years=-1, months=5),
    )
    customer = lease.customer

    user = UserFactory()

    data = {
        "id": to_global_id(ProfileNode, customer.id),
        "first_name": user.first_name,
        "last_name": user.last_name,
        "primary_email": {
            "email": user.email
        },
        "primary_phone": {
            "phone": faker.phone_number()
        },
    }

    assert Order.objects.count() == 0

    with mock.patch(
            "customers.services.profile.requests.post",
            side_effect=mocked_response_profile(count=0, data=data),
    ):
        with mock.patch(
                "payments.utils.send_notification",
                side_effect=AnymailError("Anymail error"),
        ):
            invoicing_service = BerthInvoicingService(
                request=RequestFactory().request(), profile_token="token")
            invoicing_service.send_invoices()

    assert len(invoicing_service.successful_orders) == 0
    assert len(invoicing_service.failed_orders) == 1
    assert len(invoicing_service.failed_leases) == 0
    assert Order.objects.count() == 1

    order = Order.objects.first()

    assert order.id in invoicing_service.failed_orders[0].keys()
    assert order.comment == "01-01-2020 10:00:00: Anymail error"
    assert order.due_date is None
    assert invoicing_service.failed_orders[0].get(order.id) == "Anymail error"

    assert len(mail.outbox) == 0

    leases = BerthLease.objects.exclude(id=lease.id)
    assert leases.count() == 1
    lease: BerthLease = leases.first()
    assert lease.status == LeaseStatus.ERROR
    assert "Error with the order, check the order first" in lease.comment
    assert lease.start_date.isoformat() == "2020-06-10"
    assert lease.end_date.isoformat() == "2020-09-14"

    assert order.status == OrderStatus.ERROR
    assert (order.log_entries.get(to_status=OrderStatus.ERROR).comment ==
            "Lease renewing failed: Anymail error")