combo/tests/test_import_export.py

79 lines
2.2 KiB
Python

from cStringIO import StringIO
import datetime
import json
import os
import shutil
import sys
import tempfile
import pytest
from django.core.management import call_command
from combo.data.models import Page, TextCell
from combo.data.utils import export_site, import_site
pytestmark = pytest.mark.django_db
@pytest.fixture
def some_data():
page = Page(title='One', slug='one')
page.save()
page = Page(title='Two', slug='two')
page.save()
page = Page(title='Three', slug='three')
page.save()
cell = TextCell(page=page, order=0, text='hello world')
cell.save()
def get_output_of_command(command, *args, **kwargs):
old_stdout = sys.stdout
output = sys.stdout = StringIO()
call_command(command, *args, **kwargs)
sys.stdout = old_stdout
return output.getvalue()
def test_import_export(app, some_data):
output = get_output_of_command('export_site')
assert len(json.loads(output)['pages']) == 3
import_site(data={}, clean=True)
assert Page.objects.all().count() == 0
assert TextCell.objects.all().count() == 0
empty_output = get_output_of_command('export_site')
assert len(json.loads(empty_output)['pages']) == 0
Page(title='test', slug='test').save()
old_stdin = sys.stdin
sys.stdin = StringIO(json.dumps({}))
assert Page.objects.count() == 1
try:
call_command('import_site', '-', clean=True)
finally:
sys.stdin = old_stdin
assert Page.objects.count() == 0
with tempfile.NamedTemporaryFile() as f:
f.write(output)
f.flush()
call_command('import_site', f.name)
assert Page.objects.count() == 3
assert TextCell.objects.all().count() == 1
import_site(data={}, if_empty=True)
assert Page.objects.count() == 3
assert TextCell.objects.all().count() == 1
import_site(data=[], clean=True)
tempdir = tempfile.mkdtemp('chrono-test')
empty_output = get_output_of_command('export_site', output=os.path.join(tempdir, 't.json'))
assert os.path.exists(os.path.join(tempdir, 't.json'))
shutil.rmtree(tempdir)
def test_backward_compatibility_import(app, some_data):
old_export = Page.export_all_for_json()
Page.objects.all().delete()
import_site(data=old_export)
assert Page.objects.count() == 3