【问题标题】:Testing csv file stored in memory using unittest django使用 unittest django 测试存储在内存中的 csv 文件
【发布时间】:2015-11-03 11:38:57
【问题描述】:

尝试写入 csv 文件时出现错误。这是我的两个脚本:

Tasks.py

def get_data():

          customer = Customer.objects.all()
          csvfile = StringIO.StringIO()
          csvwriter = csv.writer(csvfile)

          for i in customers:
              csvwriter.writerow([str(i.phone_number)])

          return csvfile

在tests.py中:

    with open(get_data().getvalue(), 'rb') as myfile:
        data = [row for row in csv.reader(myfile.read().splitlines())]
        print data

这是错误:

IOError: [Errno 2] No such file or directory: '999999999\r\n'

其中 '999999999' 应该写入文件中。

我该如何解决这个问题?

【问题讨论】:

  • 你为什么要打开它?它不是一个文件。 get_data 是一个可以直接读取的 StringIO 对象。
  • 好吧,有道理。谢谢!

标签: python django unit-testing csv testing


【解决方案1】:

您的 get_data() 函数不返回文件,而是返回 StringIO 对象。你不需要open()它,你可以这样读:

myfile = get_data().getvalue()
data = [row for row in csv.reader(myfile.splitlines())]
print data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2017-09-08
    • 2012-10-19
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多