def test_has_all_required_metadata(self): scenario = ScenarioF.create() scenariobreach = ScenarioBreachF.create( scenario=scenario, extwbaselevel=None) if1 = InputFieldF.build( destination_table='Scenario', destination_field='whee', required=True) if2 = InputFieldF.build( destination_table='ScenarioBreach', destination_field='extwbaselevel', required=True) self.assertFalse(scenario.has_values_for((if1,))) scenario.whee = "something" self.assertTrue(scenario.has_values_for((if1,))) self.assertFalse(scenario.has_values_for((if1, if2))) scenariobreach.extwbaselevel = 3.0 scenariobreach.save() del scenario._data_objects # Clear cache self.assertTrue(scenario.has_values_for((if1, if2)))
def test_xy(self): WGS_X = 10 WGS_Y = 20 RD_X = 110 RD_Y = 120 breach = FakeObject( geom=FakeObject( x=WGS_X, y=WGS_Y)) inputfieldx = InputFieldF.build( name='X coordinaat', destination_table='Breach', destination_field='geom') inputfieldy = InputFieldF.build( name='Y coordinaat', destination_table='Breach', destination_field='geom') with mock.patch( 'flooding_lib.coordinates.wgs84_to_rd', return_value=(RD_X, RD_Y)): retvaluex = models.find_imported_value( inputfieldx, {'breach': breach}) retvaluey = models.find_imported_value( inputfieldy, {'breach': breach}) self.assertEquals(retvaluex, RD_X) self.assertEquals(retvaluey, RD_Y)
def test_getitem(self): name = u"dit is een input field" InputFieldF.create(name=name) header = eie.ImportedHeader() foundfield = header.find_field_by_name(1, name) self.assertTrue(header[1] is foundfield)
def test_exception_if_occurs_twice(self): name = "dit is een input field" InputFieldF.create(name=name) header = eie.ImportedHeader() header.find_field_by_name(1, name) self.assertRaises(eie.ImportedHeader.HeaderException, lambda: header.find_field_by_name(2, name))
def test_exception_if_occurs_twice(self): name = u"dit is een input field" InputFieldF.create(name=name) header = eie.ImportedHeader() header.find_field_by_name(1, name) self.assertRaises(eie.ImportedHeader.HeaderException, lambda: header.find_field_by_name(2, name))
def setUp(self): # Lots of setup InputFieldF.create(name="Scenario Identificatie") self.approvalobjecttype = testapprovalmodels.ApprovalObjectTypeF() self.approvalrule = approvalmodels.ApprovalRule.objects.create(name="some rule", description="some description") self.approvalobjecttype.approvalrule.add(self.approvalrule) self.project = ProjectF.create(approval_object_type=self.approvalobjecttype) self.scenario = ScenarioF.create(name="scenario name") self.scenario.set_project(self.project)
def setUp(self): # Lots of setup InputFieldF.create(name='Scenario Identificatie') self.approvalobjecttype = testapprovalmodels.ApprovalObjectTypeF() self.approvalrule = approvalmodels.ApprovalRule.objects.create( name="some rule", description="some description") self.approvalobjecttype.approvalrule.add(self.approvalrule) self.project = ProjectF.create( approval_object_type=self.approvalobjecttype) self.scenario = ScenarioF.create(name="scenario name") self.scenario.set_project(self.project)
def test_false_at_incorrect_options(self): inputfield = InputFieldF.build(type=InputField.TYPE_SELECT, options="not a dictionary at all!") header = {'fieldtype': 'Select', 'inputfield': inputfield} self.assertFalse(eie.write_domeinlijst(None, 0, header))
def test_a_string_isnt_a_dict(self): inputfield = InputFieldF.build( type=InputField.TYPE_SELECT, options=repr("not a dictionary at all!")) header = {'fieldtype': 'Select', 'inputfield': inputfield} self.assertFalse(eie.write_domeinlijst(None, 0, header))
def test_set_value_raises_not_implemented(self): """The function supports only a few destination tables, should raise NotImplementedError if another table is asked for.""" scenario = ScenarioF.build() inputfield = InputFieldF.build(destination_table="Project") self.assertRaises( NotImplementedError, lambda: scenario.set_value_for_inputfield(inputfield, None))
def test_add_extra_header_fields_hint(self): """header['fieldhint'] should be equal to the field's excel hint.""" inputfield = InputFieldF(excel_hint='test 123') fieldinfo = eie.FieldInfo([]) header = fieldinfo.add_extra_header_fields({'inputfield': inputfield}) self.assertEquals(header['fieldhint'], 'test 123')
def test_get_integer_from_scenario(self): scenario = FakeObject(field=3) inputfield = InputFieldF.build(destination_table='Scenario', destination_field='field') retvalue = models.find_imported_value(inputfield, {'scenario': scenario}) self.assertEquals(retvalue, 3)
def test_add_extra_header_fields_name(self): """header['fieldname'] should be equal to the field's name.""" inputfield = InputFieldF(name='test 123') fieldinfo = eie.FieldInfo([]) header = fieldinfo.add_extra_header_fields({'inputfield': inputfield}) self.assertEquals(header['fieldname'], 'test 123')
def test_can_iterate(self): name = u"dit is een input field" field = InputFieldF.create(name=name) header = eie.ImportedHeader() header.find_field_by_name(1, name) for i, iterfield in enumerate(header): self.assertEquals(i, 0) # We should only come here once self.assertEquals(field, iterfield)
def test_set_value_raises_not_implemented(self): """The function supports only a few destination tables, should raise NotImplementedError if another table is asked for.""" scenario = ScenarioF.build() inputfield = InputFieldF.build( destination_table="Project") self.assertRaises( NotImplementedError, lambda: scenario.set_value_for_inputfield(inputfield, None))
def test_skips_empty_cell(self, mocked_setvalue): """If a cell isn't filled in, skip it.""" inputfield = InputFieldF.build(destination_table="Scenario", type=InputField.TYPE_INTEGER) cell = MockCell(value="") header = self.build_header(inputfield) eie.import_scenario_row(header, 66, self.rowstart + [cell], self.allowed_ids) self.assertFalse(mocked_setvalue.called)
def test_get_integer_from_scenario(self): scenario = FakeObject(field=3) inputfield = InputFieldF.build( destination_table='Scenario', destination_field='field') retvalue = models.find_imported_value( inputfield, {'scenario': scenario}) self.assertEquals(retvalue, 3)
def test_skips_ignored_inputfield(self, mocked_setvalue): """Some destination tables, e.g. Project, can't be modified from this import and should be skipped.""" inputfield = InputFieldF.build(destination_table="Project", type=InputField.TYPE_INTEGER) cell = MockCell(value=3) header = self.build_header(inputfield) eie.import_scenario_row(header, 66, self.rowstart + [cell], self.allowed_ids) self.assertFalse(mocked_setvalue.called)
def test_finds_field(self): name = u"dit is een input field" field = InputFieldF.create(name=name) fields = {} header = eie.ImportedHeader(fields) foundfield = header.find_field_by_name(1, name) self.assertEquals(field, foundfield) self.assertTrue(fields[1] is foundfield)
def test_a_string_isnt_a_dict(self): inputfield = InputFieldF.build( type=InputField.TYPE_SELECT, options=repr("not a dictionary at all!")) header = { 'fieldtype': 'Select', 'inputfield': inputfield } self.assertFalse(eie.write_domeinlijst(None, 0, header))
def test_false_at_incorrect_options(self): inputfield = InputFieldF.build( type=InputField.TYPE_SELECT, options="not a dictionary at all!") header = { 'fieldtype': 'Select', 'inputfield': inputfield } self.assertFalse(eie.write_domeinlijst(None, 0, header))
def test_wrong_value_raises_error(self): """A nonsensical value in a cell returns an error message.""" inputfield = InputFieldF.build(destination_table="scenario", type=InputField.TYPE_INTEGER) cell = MockCell(value="whee") header = self.build_header(inputfield) errors = eie.import_scenario_row(header, 66, self.rowstart + [cell], self.allowed_ids) self.assertEquals(len(errors), 1) self.assertTrue("66" in errors[0])
def test_add_extra_header_fields_type_date(self): """header['fieldtype'] should be equal to a specific string in case the inputfield's type is TYPE_DATE.""" inputfield = InputFieldF(type=InputField.TYPE_DATE, destination_table='Scenario') fieldinfo = eie.FieldInfo([]) header = fieldinfo.add_extra_header_fields({'inputfield': inputfield}) self.assertEquals(header['fieldtype'], u'Datum (DD/MM/JJJJ)')
def test_skips_empty_cell(self, mocked_setvalue): """If a cell isn't filled in, skip it.""" inputfield = InputFieldF.build(destination_table='Scenario', type=InputField.TYPE_INTEGER) cell = MockCell(value=u'') header = self.build_header(inputfield) eie.import_scenario_row(header, 66, self.rowstart + [cell], self.allowed_ids) self.assertFalse(mocked_setvalue.called)
def test_add_extra_header_fields_type_ignored(self): """If an inputfield is ignored, we place a notice in the type field""" inputfield = InputFieldF(type=InputField.TYPE_DATE, destination_table='Project') fieldinfo = eie.FieldInfo([]) header = fieldinfo.add_extra_header_fields({'inputfield': inputfield}) # Field type contains a text within ( ) self.assertTrue(header['fieldtype'].startswith('(') and header['fieldtype'].endswith(')'))
def test_one_inputfield_one_code(self): worksheet = mock.MagicMock() inputfield = InputFieldF.build(type=InputField.TYPE_SELECT, options=repr({1: "first line"})) header = {"fieldtype": "Select", "inputfield": inputfield, "fieldname": "Test"} self.assertTrue(eie.write_domeinlijst(worksheet, 0, header)) expected = [mock.call(0, 0, "Code"), mock.call(0, 1, "Test"), mock.call(1, 0, 1), mock.call(1, 1, "first line")] self.assertEquals(worksheet.write.call_args_list, expected)
def test_rest_calls_value_for_inputfield(self): field_value = 3 inputfield = InputFieldF.build(type=InputField.TYPE_INTEGER) with mock.patch("flooding_lib.models.Scenario.value_for_inputfield", return_value=field_value) as patched: headers = ({}, {"inputfield": inputfield}) scenariorow = eie.ScenarioRow(ScenarioF.build(), headers) columns = scenariorow.columns() columns.next() # Skip scenario id self.assertEquals(columns.next().value, field_value) patched.assert_called_with(inputfield)
def test_skips_ignored_inputfield(self, mocked_setvalue): """Some destination tables, e.g. Project, can't be modified from this import and should be skipped.""" inputfield = InputFieldF.build(destination_table='Project', type=InputField.TYPE_INTEGER) cell = MockCell(value=3) header = self.build_header(inputfield) eie.import_scenario_row(header, 66, self.rowstart + [cell], self.allowed_ids) self.assertFalse(mocked_setvalue.called)
def test_wrong_value_raises_error(self): """A nonsensical value in a cell returns an error message.""" inputfield = InputFieldF.build(destination_table='scenario', type=InputField.TYPE_INTEGER) cell = MockCell(value="whee") header = self.build_header(inputfield) errors = eie.import_scenario_row(header, 66, self.rowstart + [cell], self.allowed_ids) self.assertEquals(len(errors), 1) self.assertTrue("66" in errors[0])
def test_rest_calls_value_for_inputfield(self): field_value = 3 inputfield = InputFieldF.build(type=InputField.TYPE_INTEGER) with mock.patch('flooding_lib.models.Scenario.value_for_inputfield', return_value=field_value) as patched: headers = ({}, {'inputfield': inputfield}) scenariorow = eie.ScenarioRow(ScenarioF.build(), headers) columns = scenariorow.columns() columns.next() # Skip scenario id self.assertEquals(columns.next().value, field_value) patched.assert_called_with(inputfield)
def test_some_inputfield(self, mocked_setvalue): """Test with an integer inputfield and see what happens.""" inputfield = InputFieldF.build(destination_table="scenario", type=InputField.TYPE_INTEGER) cell = MockCell(value=3) header = self.build_header(inputfield) eie.import_scenario_row(header, 66, self.rowstart + [cell], self.allowed_ids) self.assertTrue(mocked_setvalue.called) c_inputfield, c_value = mocked_setvalue.call_args[0] self.assertTrue(c_inputfield is inputfield) self.assertTrue(isinstance(c_value, IntegerValue))
def test_headers_from_inputfields(self): """Test that it uses the headers from grouped_input_fields().""" inputfield = InputFieldF.build(name="testfield") grouped_input_fields = [{"id": 1, "title": "testheader", "fields": [inputfield]}] with mock.patch( "flooding_lib.tools.importtool.models.InputField.grouped_input_fields", return_value=grouped_input_fields ): fieldinfo = eie.FieldInfo([]) headers = list(fieldinfo.headers_from_inputfields()) self.assertEquals(len(headers), 1) self.assertEquals(headers[0]["headername"], "testheader") self.assertEquals(headers[0]["inputfield"], inputfield)
def test_add_extra_header_fields_type(self): """header['fieldtype'] should be equal to the translated version of the choice's description.""" activate('nl') inputfield = InputFieldF(type=InputField.TYPE_STRING, destination_table='Scenario') fieldinfo = eie.FieldInfo([]) header = fieldinfo.add_extra_header_fields({'inputfield': inputfield}) self.assertEquals(header['fieldtype'], u'Tekst') deactivate()
def test_set_value_for_inputfield_sets_extrascenarioinfo(self): """See if an inputfield using ExtraScenarioInfo is set.""" scenario = ScenarioF.create() ExtraInfoFieldF.create(name="test") inputfield = InputFieldF.build(destination_table='ExtraScenarioInfo', destination_field='test', type=importmodels.InputField.TYPE_FLOAT) value_object = inputfield.build_value_object() value_object.set(0.5) scenario.set_value_for_inputfield(inputfield, value_object) # Was it saved? esi = models.ExtraScenarioInfo.get(scenario, 'test') self.assertEquals(esi.value, u'0.5')
def test_simple_scenario_info(self): scenario = ScenarioF.create() fieldname = 'test' value = 3 extrainfofield = ExtraInfoFieldF.create(name=fieldname) ExtraScenarioInfoF.create(scenario=scenario, extrainfofield=extrainfofield, value=value) inputfield = InputFieldF.build(destination_table='ExtraScenarioInfo', destination_field=fieldname) retvalue = models.find_imported_value(inputfield, {'scenario': scenario}) self.assertEquals(retvalue, 3)
def test_headers_from_inputfields(self): """Test that it uses the headers from grouped_input_fields().""" inputfield = InputFieldF.build(name="testfield") grouped_input_fields = [{ 'id': 1, 'title': 'testheader', 'fields': [ inputfield]}] with mock.patch( 'flooding_lib.tools.importtool.models.InputField.grouped_input_fields', return_value=grouped_input_fields): fieldinfo = eie.FieldInfo([]) headers = list(fieldinfo.headers_from_inputfields()) self.assertEquals(len(headers), 1) self.assertEquals(headers[0]['headername'], 'testheader') self.assertEquals(headers[0]['inputfield'], inputfield)
def test_some_inputfield(self, mocked_setvalue): """Test with an integer inputfield and see what happens.""" inputfield = InputFieldF.build(destination_table='scenario', type=InputField.TYPE_INTEGER) cell = MockCell(value=3) header = self.build_header(inputfield) eie.import_scenario_row(header, 66, self.rowstart + [cell], self.allowed_ids) self.assertTrue(mocked_setvalue.called) c_inputfield, c_value = mocked_setvalue.call_args[0] self.assertTrue(c_inputfield is inputfield) self.assertTrue(isinstance(c_value, IntegerValue))
def test_set_value_for_inputfield_sets_extrascenarioinfo(self): """See if an inputfield using ExtraScenarioInfo is set.""" scenario = ScenarioF.create() ExtraInfoFieldF.create(name="test") inputfield = InputFieldF.build( destination_table='ExtraScenarioInfo', destination_field='test', type=importmodels.InputField.TYPE_FLOAT) value_object = inputfield.build_value_object() value_object.set(0.5) scenario.set_value_for_inputfield(inputfield, value_object) # Was it saved? esi = models.ExtraScenarioInfo.get(scenario, 'test') self.assertEquals(esi.value, u'0.5')
def test_set_value_for_inputfield_on_scenario_sets_value(self): """See if a value is really set.""" scenario = ScenarioF.create() inputfield = InputFieldF.build( destination_table='Scenario', destination_field='name', type=importmodels.InputField.TYPE_STRING) value_object = inputfield.build_value_object() value_object.set("new name") scenario.set_value_for_inputfield(inputfield, value_object) # Was it saved? scenario = models.Scenario.objects.get(pk=scenario.id) self.assertEquals(scenario.name, "new name")
def trivial_test(self): inputfield = InputFieldF.create() mock_result = mock.MagicMock() mock_result.scenario.value_for_inputfield.return_value = 100.0 / 24 grid = numpy.array([-999, 0, 50, 150]) # -999 must be untouched # 0 and are too low, untouched # 100 should be subtracted from 150 with mock.patch( 'flooding_lib.tasks.' 'png_generation.INPUTFIELD_STARTMOMENT_BREACHGROWTH_ID', new=inputfield.id): png_generation.correct_gridta(grid, mock_result) self.assertTrue((grid == numpy.array([-999, 0, 50, 50])).all())
def test_simple_scenario_info(self): scenario = ScenarioF.create() fieldname = 'test' value = 3 extrainfofield = ExtraInfoFieldF.create(name=fieldname) ExtraScenarioInfoF.create( scenario=scenario, extrainfofield=extrainfofield, value=value) inputfield = InputFieldF.build( destination_table='ExtraScenarioInfo', destination_field=fieldname) retvalue = models.find_imported_value( inputfield, {'scenario': scenario}) self.assertEquals(retvalue, 3)
def test_headers_from_inputfields(self): """Test that it uses the headers from grouped_input_fields().""" inputfield = InputFieldF.build(name="testfield") grouped_input_fields = [{ 'id': 1, 'title': 'testheader', 'fields': [inputfield] }] with mock.patch( 'flooding_lib.tools.importtool.models.InputField.grouped_input_fields', return_value=grouped_input_fields): fieldinfo = eie.FieldInfo([]) headers = list(fieldinfo.headers_from_inputfields()) self.assertEquals(len(headers), 1) self.assertEquals(headers[0]['headername'], 'testheader') self.assertEquals(headers[0]['inputfield'], inputfield)
def test_set_value_for_inputfield_sets_scenariobreach_value(self): """See if an inputfield using ScenarioBreach is set.""" scenario = ScenarioF.create() ScenarioBreachF.create(scenario=scenario) inputfield = InputFieldF.build(destination_table='ScenarioBreach', destination_field='widthbrinit', type=importmodels.InputField.TYPE_FLOAT) value_object = inputfield.build_value_object() value_object.set(0.5) scenario.set_value_for_inputfield(inputfield, value_object) # Was it saved? if hasattr(scenario, '_data_objects'): del scenario._data_objects scenariobreach = scenario.gather_data_objects()['scenariobreach'] self.assertEquals(scenariobreach.widthbrinit, 0.5)
def test_999(self): # It used to be that values like -999 were treated separately # (as if they were None), but that is disabled now so this is # just a pretty random test. scenario = ScenarioF.create() fieldname = 'test' value = '-999' extrainfofield = ExtraInfoFieldF.create(name=fieldname) ExtraScenarioInfoF.create(scenario=scenario, extrainfofield=extrainfofield, value=value) inputfield = InputFieldF.build( destination_table='ExtraScenarioInfo', destination_field=fieldname, type=importmodels.InputField.TYPE_STRING) retvalue = models.find_imported_value(inputfield, {'scenario': scenario}) self.assertEquals(retvalue, u'-999')
def test_set_value_for_inputfield_sets_scenariobreach_value(self): """See if an inputfield using ScenarioBreach is set.""" scenario = ScenarioF.create() ScenarioBreachF.create(scenario=scenario) inputfield = InputFieldF.build( destination_table='ScenarioBreach', destination_field='widthbrinit', type=importmodels.InputField.TYPE_FLOAT) value_object = inputfield.build_value_object() value_object.set(0.5) scenario.set_value_for_inputfield(inputfield, value_object) # Was it saved? if hasattr(scenario, '_data_objects'): del scenario._data_objects scenariobreach = scenario.gather_data_objects()['scenariobreach'] self.assertEquals(scenariobreach.widthbrinit, 0.5)
def test_999(self): # It used to be that values like -999 were treated separately # (as if they were None), but that is disabled now so this is # just a pretty random test. scenario = ScenarioF.create() fieldname = 'test' value = '-999' extrainfofield = ExtraInfoFieldF.create(name=fieldname) ExtraScenarioInfoF.create( scenario=scenario, extrainfofield=extrainfofield, value=value) inputfield = InputFieldF.build( destination_table='ExtraScenarioInfo', destination_field=fieldname, type=importmodels.InputField.TYPE_STRING) retvalue = models.find_imported_value( inputfield, {'scenario': scenario}) self.assertEquals(retvalue, u'-999')
def test_one_inputfield_one_code(self): worksheet = mock.MagicMock() inputfield = InputFieldF.build(type=InputField.TYPE_SELECT, options=repr({1: "first line"})) header = { 'fieldtype': 'Select', 'inputfield': inputfield, 'fieldname': 'Test' } self.assertTrue(eie.write_domeinlijst(worksheet, 0, header)) expected = [ mock.call(0, 0, "Code"), mock.call(0, 1, "Test"), mock.call(1, 0, 1), mock.call(1, 1, "first line") ] self.assertEquals(worksheet.write.call_args_list, expected)
def test_date_inputfield_has_number_format(self, mocked_make_style): inputfield = InputFieldF(type=InputField.TYPE_DATE) eie.Cell(40725.0, inputfield=inputfield) num_format = mocked_make_style.call_args[0][1] self.assertEquals(num_format, 'dd/mm/yyyy')