小编Tam*_*erz的帖子

在Python中编写.CSV文件,适用于Windows中的Python 2.7+和Python 3.3+

编辑:我把它放在标题中,但只是意识到我没有在体内提到它.这似乎是Windows特有的.

我很难csv在一个兼容Python 2.7和3.3的脚本中使用Python模块编写输出.

第一次尝试在Python 2.7中按预期工作:

with open('test.csv', 'wb') as csv_file:
    writer = csv.DictWriter(csv_file, ['header1', 'header2'])
    writer.writeheader()
    for item in items:
        writer.writerow(item)
Run Code Online (Sandbox Code Playgroud)

但是,当在Python 3.3中运行同样的事情时,你最终得到:

TypeError: 'str' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)

所以我改变'wb''wt'它运行,但现在我有一个额外的空白行中的文件每隔一行.

为了解决这个问题,我改变了:

with open('test.csv', 'wt') as csv_file:
Run Code Online (Sandbox Code Playgroud)

至:

with open('test.csv', 'wt', newline='') as csv_file:
Run Code Online (Sandbox Code Playgroud)

但现在,它打破了Python 2.7:

TypeError: 'newline' is an invalid keyword argument for this function
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

try:
    with open('test.csv', 'wt', newline='') as csv_file:
        writer = csv.DictWriter(csv_file, ['header1', 'header2'])
        writer.writeheader()
        for item in …
Run Code Online (Sandbox Code Playgroud)

python csv python-2.7 python-3.x python-3.3

15
推荐指数
2
解决办法
2万
查看次数

模拟ftplib.FTP以进行单元测试Python代码

我不知道为什么我只是没有得到这个,但我想在Python中使用mock来测试我的函数是否在ftplib.FTP中正确调用函数.我把所有东西简化了下来,但仍然没有把它包裹起来.这是一个简单的例子:

import unittest
import ftplib
from unittest.mock import patch

def download_file(hostname, file_path, file_name):
    ftp = ftplib.FTP(hostname)
    ftp.login()
    ftp.cwd(file_path)

class TestDownloader(unittest.TestCase):

    @patch('ftplib.FTP')
    def test_download_file(self, mock_ftp):
        download_file('ftp.server.local', 'pub/files', 'wanted_file.txt')

        mock_ftp.cwd.assert_called_with('pub/files')
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到:

AssertionError: Expected call: cwd('pub/files')
Not called
Run Code Online (Sandbox Code Playgroud)

我知道它必须使用模拟对象,因为这是一个虚假的服务器名称,并且在没有修补的情况下运行时,它会抛出"socket.gaierror"异常.

如何获取功能正在运行的实际对象?长期目标是在同一文件中没有"download_file"函数,而是从单独的模块文件中调用它.

python unit-testing python-mock

10
推荐指数
1
解决办法
3157
查看次数

如何使用 Python 的单元测试正确比较两个 SQLAlchemy Column 对象?

我编写了一个单元测试,该测试应该比较从我的方法返回的 Column 对象。我在测试中创建一个,然后从我的班级中获取一个。我的测试代码如下所示:

def test_getting_correct_sa_object_from_column(self):
    table = self.database.get_table_by_name('ESEventlogMain')
    column = table.get_column_by_name('eventdata')
    sa_column = sqlalchemy.Column('eventdata', sqlalchemy.Integer, primary_key=False)

    self.assertEqual(sa_column, column.get_sa_object())
Run Code Online (Sandbox Code Playgroud)

我的类的方法返回的是:

def get_sa_object(self):
    if self.type == 'int':
        sa_type = sqlalchemy.Integer
    elif self.type == 'varchar':
        sa_type = sqlalchemy.String(self.length)

    return sqlalchemy.Column(self.name, sa_type, primary_key=self.is_primary_key)
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,它失败并显示以下输出:

Failure
Traceback (most recent call last):
  File "C:\Users\tames.mctigue\PycharmProjects\db_setup_wizard\tests.py", line 107, in test_getting_correct_sa_object_from_column
    self.assertEqual(sa_column, column.get_sa_object())
AssertionError: Column('eventdata', Integer(), table=None) != Column('eventdata', Integer(), table=None)
Run Code Online (Sandbox Code Playgroud)

AssertionError 显示了看起来相同的数据,因此我陷入了要寻找的内容。除了“assertEqual”之外,我还应该使用不同的比较吗?

python sqlalchemy python-unittest

5
推荐指数
1
解决办法
2798
查看次数

你如何模拟PyMySQL的返回值以便在Python中进行测试?

我正在尝试为将从MySQL数据库中提取数据的脚本设置一些测试.我在这里找到了一个看起来像我想做的例子,但它只给了我一个对象而不是结果:

<MagicMock name='pymysql.connect().cursor[38 chars]152'>

这是我正在使用的函数(simple.py):

import pymysql

def get_user_data():
    connection = pymysql.connect(host='localhost', user='user', password='password',
                                 db='db', charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    try:
        with connection.cursor() as cursor:
            sql = "SELECT `id`, `password` FROM `users`"
            cursor.execute(sql)
            results = cursor.fetchall()
    finally:
        connection.close()

    return results
Run Code Online (Sandbox Code Playgroud)

而且测试:

from unittest import TestCase, mock
import simple

class TestSimple(TestCase):

    @mock.patch('simple.pymysql', autospec=True)
    def test_get-data(self, mock_pymysql):
        mock_cursor = mock.MagicMock()
        test_data = [{'password': 'secret', 'id': 1}]
        mock_cursor.fetchall.return_value = test_data
        mock_pymysql.connect.return_value.__enter__.return_value = mock_cursor

        self.assertEqual(test_data, simple.get_user_data())
Run Code Online (Sandbox Code Playgroud)

结果:

AssertionError: [{'id': 1, 'password': 'secret'}] != …
Run Code Online (Sandbox Code Playgroud)

python unit-testing

5
推荐指数
1
解决办法
2224
查看次数