wcs/tests/test_datasource.py

97 lines
2.7 KiB
Python

import json
import sys
import shutil
from quixote import cleanup
from wcs import publisher
from wcs.qommon.http_request import HTTPRequest
from wcs.qommon.form import *
from wcs import fields, data_sources
from test_widgets import MockHtmlForm, mock_form_submission
from utilities import create_temporary_pub
def setup_module(module):
cleanup()
global pub, req
pub = create_temporary_pub()
req = HTTPRequest(None, {})
pub._set_request(req)
def teardown_module(module):
shutil.rmtree(pub.APP_DIR)
def test_item_field_python_datasource():
field = fields.ItemField()
field.id = 1
field.data_source = {
'type': 'formula',
'value': '''[('1', 'un'), ('2', 'deux')]'''
}
form = Form()
field.add_to_form(form)
widget = form.get_widget('f1')
assert widget is not None
assert widget.options == [('1', 'un', 'un'), ('2', 'deux', 'deux')]
form = MockHtmlForm(widget)
mock_form_submission(req, widget, {'f1': ['un']})
assert widget.parse() == '1'
form = Form()
field.add_to_view_form(form, value='1')
widget = form.get_widget('f1')
form = MockHtmlForm(widget)
mock_form_submission(req, widget)
assert widget.parse() == '1'
def test_python_datasource():
plain_list = repr([('1', 'foo'), ('2', 'bar')])
datasource = {'type': 'formula', 'value': repr(plain_list)}
assert data_sources.get_items(datasource) == plain_list
def test_json_datasource():
datasource = {'type': 'json', 'value': ''}
assert data_sources.get_items(datasource) == []
# missing file
json_file_path = os.path.join(pub.app_dir, 'test.json')
datasource = {'type': 'json', 'value': 'file://%s' % json_file_path}
assert data_sources.get_items(datasource) == []
# invalid json file
json_file = open(json_file_path, 'w')
json_file.write(u'foobar'.encode('zlib_codec'))
json_file.close()
assert data_sources.get_items(datasource) == []
# empty json file
json_file = open(json_file_path, 'w')
json.dump({}, json_file)
json_file.close()
assert data_sources.get_items(datasource) == []
# unrelated json file
json_file = open(json_file_path, 'w')
json.dump('foobar', json_file)
json_file.close()
assert data_sources.get_items(datasource) == []
# another unrelated json file
json_file = open(json_file_path, 'w')
json.dump({'data': 'foobar'}, json_file)
json_file.close()
assert data_sources.get_items(datasource) == []
# a good json file
json_file = open(json_file_path, 'w')
json.dump({'data': [{'id': '1', 'text': 'foo'}, {'id': '2', 'text': 'bar'}]}, json_file)
json_file.close()
assert data_sources.get_items(datasource) == [('1', 'foo', '1'), ('2', 'bar', '2')]