2

我正在努力为使用 Pyodbc 查询本地 SQL Server 数据库的 Python 编写单元测试。

以下代码运行...

import pyodbc
import random
import unittest
from EmailSender import EmailSender

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.email_sender = EmailSender()
        self.other_email_sender = EmailSender()

    def test_for_initialisation_variables(self):
        """
        Tests to check that the object is created properly
        """
        self.assertTrue(self.email_sender.server)
        self.assertTrue(self.email_sender.errorLogFile)
        self.assertTrue(self.email_sender.connection)
        self.assertTrue(self.email_sender.cursor)
        self.assertTrue(self.email_sender.siteAuth)
        self.assertTrue(self.email_sender.apiCallsLimitPerRun)

    def test_SQL_Server_Connection(self):
        for value in self.email_sender.cursor.execute("select * from sys.tables"):.
            print value

但是,当我向代码添加第二个几乎相同的测试时......

import pyodbc
import random
import unittest
from EmailSender import EmailSender

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.email_sender = EmailSender()
        self.other_email_sender = EmailSender()

    def test_for_initialisation_variables(self):
        """
        Tests to check that the object is created properly
        """
        self.assertTrue(self.email_sender.server)
        self.assertTrue(self.email_sender.errorLogFile)
        self.assertTrue(self.email_sender.connection)
        self.assertTrue(self.email_sender.cursor)
        self.assertTrue(self.email_sender.siteAuth)
        self.assertTrue(self.email_sender.apiCallsLimitPerRun)

    def test_SQL_Server_Connection(self):
        for value in self.email_sender.cursor.execute("select * from sys.tables"):.
            print value

    def test_getSites_method(self):
        for value in self.other_email_sender.cursor.execute("select * from sys.tables"):.
            print value

第三次测试失败并显示以下错误消息:

Error: ('IM001', '[IM001] [unixODBC][Driver Manager]Driver does not support this function (0) (SQLRowCount)')

ps

请注意,我一开始只创建了一个 email_sender 对象,但无法运行背靠背查询,因此将查询更改为相同,当这不起作用时,添加另一个连接和游标,这样就不会出现问题re:光标所在位置。

4

1 回答 1

2

找到了解决方案 - 基本上问题出在(默认)tearDown 方法中。

发生了一些事情,所以光标没有被重置 - 我用下面的方法覆盖了那个方法,嘿,很快,它起作用了:

def tearDown(self):
    """
    Make sure we reset the cursor
    """
    if self.email_sender.connection:
        self.email_sender.connection.close()
    del self.email_sender
于 2013-09-05T13:32:45.813 回答