예제 #1
0
 def execute(self, query, params=None):
     if self.closed:
         raise InterfaceError('Cursor is closed')
     super().execute(convert_sql(query, params))
     self._rows = collections.deque(super().fetchall())
     if self._transaction._autocommit:
         self._transaction._connection.commit()
예제 #2
0
    def test_db_connection_interface_error(self, mock_reset_db,
                                           mock_get_or_create):
        """
        Test that if an InterfaceError or OperationalError is raised,
        Handler._reset_db_connection() is called
        """
        class MockException(Exception):
            pass

        mock_get_or_create.side_effect = [
            InterfaceError(),
            OperationalError(),
            MockException()
        ]

        loop = asyncio.get_event_loop()
        with self.settings(CONTENT_APP_TTL=1):
            try:
                loop.run_until_complete(_heartbeat())
            except MockException:
                pass
        loop.close()

        mock_get_or_create.assert_called()
        mock_reset_db.assert_has_calls([call(), call()])
예제 #3
0
    def test_retry_store_result_fails(self):
        """
        Test the retry logic for InterfaceErrors.
        When result_backend_always_retry is False,
        and an InterfaceError is raised during _store_result(),
        then the InterfaceError will be re-raised.
        """
        m = self.create_task_result()
        assert set(TaskResult.objects.all()) == set(
            TaskResult.objects.using('secondary').all())

        always_retry = self.app.conf.get('result_backend_always_retry')
        self.app.conf.result_backend_always_retry = False
        backend = DatabaseBackend(self.app)

        with patch.object(backend,
                          '_store_result',
                          side_effect=[InterfaceError('Connection closed')
                                       ]) as patched_store_result:
            with patch.object(backend,
                              'exception_safe_to_retry',
                              return_value=backend.exception_safe_to_retry
                              ) as patched_safe_to_retry:
                # InterfaceError should be re-raised
                with pytest.raises(InterfaceError):
                    backend.store_result(m.task_id,
                                         result=states.SUCCESS,
                                         state=states.SUCCESS)
                assert patched_safe_to_retry.call_count == 0
                assert patched_store_result.call_count == 1

        self.app.conf.result_backend_always_retry = always_retry
        if always_retry is None:
            del self.app.conf.result_backend_always_retry
예제 #4
0
 def test_list_provider_exception_return_424(self, mocked_list):
     """Test that 424 is returned when view raises InterfaceError."""
     mocked_list.side_effect = InterfaceError("connection already closed")
     url = reverse("provider-list")
     client = APIClient()
     response = client.get(url, **self.headers)
     self.assertEqual(response.status_code,
                      status.HTTP_424_FAILED_DEPENDENCY)
예제 #5
0
파일: cursor.py 프로젝트: nakagami/djmssql
 def execute(self, query, params=None):
     if self.closed:
         raise InterfaceError('Cursor is closed')
     try:
         q = convert_sql(query, params)
         super().execute(q)
         self.query = q
     except Database.OperationalError as e:
         if e.err_num != 15225:
             raise e
예제 #6
0
def dlt_push(num, count):
    django.setup()
    try:
        # ordering = ['-created']
        dlts = DLT.objects.filter(num=num)[:count]
    except IndexError as e:
        raise InterfaceError(f'There must be {count} items.')

    msg = render_to_string('dlt_template.html', {
        'dlts': dlts,
        'now': timezone.now()
    })
    mail_sent = send_mail('[天降祥瑞]',
                          'Ritch Text Error',
                          '*****@*****.**',
                          settings.EMAIL_TO,
                          fail_silently=False,
                          html_message=msg)
    return mail_sent
예제 #7
0
    def test_retry_store_result_succeeds(self):
        """
        Test the retry logic for InterfaceErrors.
        When result_backend_always_retry is True,
        and an InterfaceError is raised during _store_result(),
        then the InterfaceError will be hidden,
        the connection to the database will be closed,
        and then automatically reopened for the next retry.
        """
        m = self.create_task_result()
        assert set(TaskResult.objects.all()) == set(
            TaskResult.objects.using('secondary').all())

        always_retry = self.app.conf.get('result_backend_always_retry')
        self.app.conf.result_backend_always_retry = True
        backend = DatabaseBackend(self.app)

        with patch.object(backend,
                          '_store_result',
                          side_effect=[
                              InterfaceError('Connection closed'),
                              backend._store_result
                          ]) as patched_store_result:
            with patch.object(backend,
                              'exception_safe_to_retry',
                              return_value=backend.exception_safe_to_retry
                              ) as patched_safe_to_retry:
                # InterfaceError should be hidden
                # And new connection opened
                # Then unpatched function called for retry
                backend.store_result(m.task_id,
                                     result=states.SUCCESS,
                                     state=states.SUCCESS)
                assert patched_safe_to_retry.call_count == 1
                assert patched_store_result.call_count == 2

        self.app.conf.result_backend_always_retry = always_retry
        if always_retry is None:
            del self.app.conf.result_backend_always_retry
예제 #8
0
def test_assure_db(mocker):
    body = "{}"
    mock_message = mocker.Mock()
    conns = [mocker.Mock(), mocker.Mock(), mocker.Mock(), mocker.Mock()]
    conns[0].close_if_unusable_or_obsolete.side_effect = InterfaceError(
        'connection already closed')
    conns[1].close_if_unusable_or_obsolete.side_effect = DatabaseError(
        'pgbouncer cannot connect to server SSL connection has been closed unexpectedly'
    )

    mocker.patch('django.db.connections.all', return_value=conns)
    assure_db_connection(body, mock_message)

    conns[0].close_if_unusable_or_obsolete.assert_called_with()
    conns[1].close_if_unusable_or_obsolete.assert_called_with()
    conns[2].close_if_unusable_or_obsolete.assert_called_with()

    with pytest.raises(DatabaseError) as e_databaseerror:
        conns = [mocker.Mock()]
        conns[0].close_if_unusable_or_obsolete.side_effect = DatabaseError(
            'Not expected error')
        mocker.patch('django.db.connections.all', return_value=conns)
        assure_db_connection(body, mock_message)
예제 #9
0
def _dlt_handler(instance, dlt):
    if not isinstance(dlt, DLT):
        raise InterfaceError('Argument dlt must be a instance of <DLT>.')

    front = set([dlt.a, dlt.b, dlt.c, dlt.d, dlt.e])
    back = set([dlt.f, dlt.g])
    front_act = set(
        [instance.a, instance.b, instance.c, instance.d, instance.e])
    back_act = set([instance.f, instance.g])

    r1 = len(front & front_act)
    r2 = len(back & back_act)

    # if r1 == 5:
    #     if r2 == 2:
    #         return '1'
    #     elif r2 == 1:
    #         return '2'
    #     return '3'
    # elif r1 == 4:
    #     if r2 == 2:
    #         return '3'
    #     elif r2 == 1:
    #         return '4'
    #     return '5'
    # elif r1 == 3:
    #     if r2 == 2:
    #         return '4'
    #     elif r2 == 1:
    #         return '5'
    #     return '6'
    # elif r1 == 2:
    #     if r2 == 2:
    #         return '5'
    #     elif r2 == 1:
    #         return '6'
    # return 0

    if r1 == 5 and r2 == 2:
        return '1'
    if r1 == 5 and r2 == 1:
        return '2'
    if r1 == 5:
        return '3'
    if r1 == 4 and r2 == 2:
        return '3'
    if r1 == 4 and r2 == 1:
        return '4'
    if r1 == 3 and r2 == 2:
        return '4'
    if r1 == 4:
        return '5'
    if r1 == 3 and r1 == 1:
        return '5'
    if r1 == 2 and r2 == 2:
        return '5'
    if r1 == 3:
        return '6'
    if r1 == 2 and r2 == 1:
        return '6'
    if r1 == 1 and r2 == 2:
        return '6'
    if r2 == 2:
        return '6'

    return '0'
예제 #10
0
파일: cursor.py 프로젝트: nakagami/djmssql
 def executemany(self, query, param_list):
     if self.closed:
         raise InterfaceError('Cursor is closed')
     for params in param_list:
         super().execute(convert_sql(query, params))