Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

DjangoのUnit Testでcsvをmockとして読み込ませる

More than 1 year has passed since last update.


import csv
from django.core.management.base import BaseCommand

class Command(BaseCommand):

    def handle(self, *args, **options):
        with open(options['file'], 'r', encoding='utf-8') as f:
            reader = csv.reader(f)
            for row in reader:
                // 処理色々


import io
from django.test import TestCase
from mock import patch

class ImportHogeHogeTest(TestCase):

    @patch("hoge.management.commands.example_command.open", create=True)
    def test_example_command(self, mock_open):
        mock_open.return_value = io.StringIO(dummy_csv_1)
        // テスト色々

dummy_csv_1 = """1,hoge,hoge_value

上記のようにすると文字列が入った変数 dummy_csv_1 をcsvファイルとして、 with open の返り値とすることができる。
このようにすると、/hoge/management/commands/example_command.py処理色々 の部分で例えば print(row[2])とするとhoge_valueが返ってくる

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away