Example #1
0
def test_DatabaseWrapper_is_usable_returns_false_if_creating_cursor_fails(
        caplog, mocker, mock_connection, mock_autocommit_methods, db_config):
    mock_connection.cursor.side_effect = pyodbc.Error("", "error message 1")
    db = DatabaseWrapper(db_config)
    db.connect()
    assert db.is_usable() is False
    assert "error message 1" in caplog.text
def getSqldatabaseODBCconn(databasename: str,
                           servername: str) -> pyodbc.connect:
    """Get ODBC DB API connection to Azure SQL Database"""

    odbcconnstring = getsqldatabaseconnectionstring(databasename=databasename,
                                                    client='odbc',
                                                    servername=servername)
    """Get the different properties from the connection string by converting it into a dictionary"""
    connectionproperties = {
        prop[0]: prop[1]
        for prop in [
            connproperty.split('=') for connproperty in odbcconnstring.strip(
                '"').rstrip(';').split(';')
        ]
    }
    """Use server and database from the connection properties derived from the connection string as mentioned above"""
    try:
        odbcconnection = pyodbc.connect("""
                                                                        Driver=SQL Server;
                                                                        Server={0};
                                                                        Database={1};
                                                                        [email protected]@XXXXXXX;
                                                                        Pwd=XXXXXXXX;
                                                                        Encrypt=yes;
                                                                        TrustServerCertificate=no;
                                                                        Connection Timeout=30;
                                                                        """.
                                        format(
                                            connectionproperties['Server'],
                                            connectionproperties['Database']))
    except Exception as e:
        raise pyodbc.Error(e)
    else:
        return odbcconnection
Example #3
0
    def test_is_disconnect(self):
        connection = Mock(spec=_ConnectionFairy)
        cursor = Mock(spec=pyodbc.Cursor)

        errors = [
            pyodbc.Error(
                "HY000",
                "[HY000] [EXASOL][EXASolution driver]Connection lost in socket read attempt. Operation timed out (-1) (SQLExecDirectW)",
            ),
            pyodbc.Error(
                "HY000",
                "[HY000] [EXASOL][EXASolution driver]Socket closed by peer."),
        ]

        for error in errors:
            status = self.dialect.is_disconnect(error, connection, cursor)
            assert status
 def test_get_rows_with_ids_exception(self):
     with patch("pyodbc.connect") as mock_connect:
         mock_connect.cursor().execute.side_effect = pyodbc.Error("Connection error")
         get_rows_with_ids(logger=self.logger, conn=mock_connect, db_name="test", schema_name="test",
                           table_name="test", columns=["test"], id_field="test", ids=[0, 1])
         self.assertTrue(mock_connect.cursor.called)
         self.assertEqual(mock_connect.cursor.mock_calls[2][0], "().execute")
         self.assertEqual(mock_connect.cursor.mock_calls[3][0], "().close")
    def test_is_disconnect(self):
        connection = Mock(spec=_ConnectionFairy)
        cursor = Mock(spec=pyodbc.Cursor)

        errors = [
            pyodbc.Error(
                'HY000',
                '[HY000] [Dremio][Dremio ODBC Driver]Connection lost in socket read attempt. Operation timed out (-1) (SQLExecDirectW)'
            ),
            pyodbc.Error(
                'HY000',
                '[HY000] [Dremio][Dremio ODBC Driver]Socket closed by peer.'),
        ]

        for error in errors:
            status = self.dialect.is_disconnect(error, connection, cursor)

            eq_(status, True)
 def test_get_last_row_id_exception(self):
     with patch("pyodbc.connect") as mock_connect:
         mock_connect.cursor().execute.side_effect = pyodbc.Error("Connection error")
         mock_connect.cursor().fetchone.return_value = [100]
         get_last_row_id(logger=self.logger, conn=mock_connect, db_name="test", schema_name="test",
                         table_name="test", id_field="test")
         self.assertTrue(mock_connect.cursor.called)
         self.assertEqual(mock_connect.cursor.mock_calls[3][0], "().execute")
         self.assertEqual(mock_connect.cursor.mock_calls[4][0], "().close")
Example #7
0
    def fetch_result(self):
        """Fetches the receiving data from the LIS for each identifier."""
        def fetchall(cursor):
            self.sql.update(resulted_items=(
                'select PID as sample_id, reportdate, panel_id, sample_assay_date, utestid, result, result_quantifier, L21.id as lis_result_id '
                'from BHPLAB.DBO.LAB21Response as L21 '
                'left join BHPLAB.DBO.LAB21ResponseQ001X0 as L21D on L21.Q001X0=L21D.QID1X0 '
                'where PID=\'{lis_specimen_identifier}\''
            ).format(dmis_column=self.dmis_column,
                     lis_specimen_identifier=self.lis_specimen_identifier))
            return cursor.execute(self.sql.get('resulted_items')).fetchall()

        if self.verbose:
            print "Querying dmis for {} resulted items".format(
                self.lis_specimen_identifier)
        try:
            with pyodbc.connect(settings.LAB_IMPORT_DMIS_DATA_SOURCE) as cnxn:
                with cnxn.cursor() as cursor:
                    for lis_specimen_identifier, report_date, panel_id, sample_assay_date, utestid, result, result_quantifier, lis_result_id in fetchall(
                            cursor):
                        try:
                            report_date = parse(report_date, dayfirst=True)
                        except AttributeError:
                            pass
                        try:
                            sample_assay_date = parse(sample_assay_date,
                                                      dayfirst=True)
                        except AttributeError:
                            pass
                        result_tuple = ResultTuple(
                            self.aliquot_identifier,
                            self.lis_specimen_identifier,
                            self.lis_subject_identifier,
                            self.lis_received_datetime, report_date, None,
                            sample_assay_date, utestid, result,
                            result_quantifier, lis_result_id)
                        self.lis_results.append(result_tuple)
                        if not self.lis_result:
                            self.lis_result = '{}{}'.format(
                                result_quantifier
                                if result_quantifier in '<>' else '', result)
                            try:
                                self.lis_result_int = int(result)
                            except TypeError:
                                pass
                            self.lis_result_qnt = result_quantifier
                            self.lis_assay = utestid
                            self.lis_assay_date = sample_assay_date
                        else:
                            print 'Warning! More than one result for {}.'.format(
                                self.aliquot_identifier)

        except pyodbc.Error as e:
            raise pyodbc.Error(e)
Example #8
0
    def fetch_receiving(self):
        """Fetches the receiving data from the LIS for each identifier."""
        def fetchall(cursor):
            self.sql.update(received_items=(
                'select pid, pat_id, headerdate from lab01response as l where '
                '{dmis_column} LIKE \'{specimen_identifier}%\''
            ).format(dmis_column=self.dmis_column,
                     specimen_identifier=self.specimen_identifier))
            return cursor.execute(self.sql.get('received_items')).fetchall()

        if self.verbose:
            print "Querying dmis for {} {}".format(self.specimen_identifier,
                                                   self.aliquot_type)
        try:
            with pyodbc.connect(settings.LAB_IMPORT_DMIS_DATA_SOURCE) as cnxn:
                with cnxn.cursor() as cursor:
                    for lis_specimen_identifier, lis_subject_identifier, lis_received_datetime in fetchall(
                            cursor):
                        self.lis_received.update({
                            lis_specimen_identifier:
                            (lis_specimen_identifier, lis_subject_identifier,
                             lis_received_datetime)
                        })
                        if lis_specimen_identifier == self.aliquot_identifier:
                            self.lis_specimen_identifier = lis_specimen_identifier
                            if not self.lis_received_datetime:
                                self.lis_received_datetime = lis_received_datetime
                            if not self.lis_subject_identifier:
                                self.lis_subject_identifier = self.subject_identifier
                                if self.lis_subject_identifier != self.subject_identifier:
                                    print "Warning! LIS pat_ref differs with EDC subject_deintifier for {}. Got {}".format(
                                        self.subject_identifier,
                                        self.lis_subject_identifier)
                            if not self.specimen_identifier:
                                self.lis_subject_identifier = self.subject_identifier
                                if self.lis_subject_identifier != self.subject_identifier:
                                    print "Warning! LIS pat_ref differs with EDC subject_deintifier for {}. Got {}".format(
                                        self.subject_identifier,
                                        self.lis_subject_identifier)

        except pyodbc.Error as e:
            raise pyodbc.Error(e)
Example #9
0
from unittest.mock import Mock, call
from datetime import timedelta

import pyodbc
import pytest
from freezegun import freeze_time

from django_informixdb.base import DatabaseWrapper

CONNECTION_FAILED_ERROR = pyodbc.Error(
    "08004",
    "Attempt to connect to database server (<dbname>) failed. (-908) (SQLDriverConnect)"
)
READ_ERROR = pyodbc.Error(
    "HY000",
    "Read error occurred during connection attempt. (-27001) (SQLDriverConnect)"
)
AUTHENTICATION_ERROR = pyodbc.Error(
    "28000",
    "Incorrect password or user is not known on the database server (-951) (SQLDriverConnect)"
)


@pytest.fixture
def db_config():
    return {
        "ENGINE": "django_informixdb",
        "SERVER": "informix",
        "NAME": "sysmaster",
        "USER": "******",
        "PASSWORD": "******",
 def timeout(self, value):
     raise pyodbc.Error('HY000',
                        "[HY000] Driver doesn't support this")
 def timeout(self, value):
     raise pyodbc.Error(
         'HY000',
         "[HY000] Couldn't set unsupported connect attribute 113 (216) (SQLSetConnectAttr)"
     )
Example #12
0
def test_create_dart_sql_server_conn_expection(config):
    with patch("pyodbc.connect", side_effect=pyodbc.Error()):
        assert create_dart_sql_server_conn(config) is None
def raise_error(*args, **kwargs):
    raise pyodbc.Error('pyodbc error')
 def test_get_connection_retry(self, mock_mysql):
     mock_mysql.side_effect = pyodbc.Error("Boom")
     connection_string = "DRIVER=testSQLServer;SERVER=test;DATABASE=testdb;UID=test;PWD=test"
     result = get_mssql_connection(logger=self.logger, connection_string=connection_string, max_attempts=2)
     self.assertIsNone(result)
 def test_insert_pyodbc_error(self, mock_exec):
     mock_exec.side_effect = pyodbc.Error()
     with self.assertRaises(MetadataManagerException):
         self.mm.insert({"foo": "bar"}, mdtype="foo")