class TestModelRunExtents(TestController):
    def setUp(self):
        super(TestModelRunExtents, self).setUp()
        self.clean_database()
        self.user = self.login()
        self.model_run_service = ModelRunService()
        with session_scope(Session) as session:
            self.driving_data = DrivingDataset()
            self.driving_data.name = "d1"
            self.driving_data.boundary_lat_north = 47.5
            self.driving_data.boundary_lat_south = 13.8
            self.driving_data.boundary_lon_east = 123.1
            self.driving_data.boundary_lon_west = -15.0
            self.driving_data.time_start = datetime.datetime(1901, 1, 1, 0, 0, 0)
            self.driving_data.time_end = datetime.datetime(2001, 1, 1, 0, 0, 0)
            session.add(self.driving_data)
            session.commit()

            self.model_run = ModelRun()
            self.model_run.name = "MR1"
            self.model_run.status = self._status(MODEL_RUN_STATUS_CREATED)
            self.model_run.driving_dataset_id = self.driving_data.id
            self.model_run.user = self.user
            self.model_run.science_configuration_id = 2

            param1 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_DRIVE_INTERP)
            pv1 = ParameterValue()
            pv1.parameter_id = param1.id
            pv1.set_value_from_python(8 * ['nf'])

            param2 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_DRIVE_DATA_PERIOD)
            pv2 = ParameterValue()
            pv2.parameter_id = param2.id
            pv2.set_value_from_python(60 * 60)

            self.model_run.parameter_values = [pv1, pv2]
            session.add(self.model_run)

    def set_up_single_cell_user_driving_data(self):
        self.clean_database()
        del self.driving_data
        self.user = self.login()
        user_upload_id = DatasetService().get_id_for_user_upload_driving_dataset()
        with session_scope(Session) as session:
            self.model_run = ModelRun()
            self.model_run.name = "MR1"
            self.model_run.status = self._status(MODEL_RUN_STATUS_CREATED)
            self.model_run.driving_dataset_id = user_upload_id
            self.model_run.user = self.user
            self.model_run.driving_data_lat = 25
            self.model_run.driving_data_lon = 40
            self.model_run.driving_data_rows = 248
            self.model_run.science_configuration_id = 2

            param1 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_DRIVE_INTERP)
            pv1 = ParameterValue()
            pv1.parameter_id = param1.id
            pv1.set_value_from_python(8 * ['nf'])

            param2 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_DRIVE_DATA_PERIOD)
            pv2 = ParameterValue()
            pv2.parameter_id = param2.id
            pv2.set_value_from_python(60 * 60)

            param3 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_DRIVE_DATA_START)
            pv3 = ParameterValue()
            pv3.parameter_id = param3.id
            pv3.value = "'1901-01-01 00:00:00'"

            param4 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_DRIVE_DATA_END)
            pv4 = ParameterValue()
            pv4.parameter_id = param4.id
            pv4.value = "'1901-01-31 21:00:00'"

            self.model_run.parameter_values = [pv1, pv2, pv3, pv4]
            session.add(self.model_run)

    def test_GIVEN_no_created_model_WHEN_page_get_THEN_redirect_to_create(self):
        self.clean_database()
        self.login()
        response = self.app.get(
            url(controller='model_run', action='extents'))
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path, is_(url(controller='model_run', action='create')), "url")

    def test_GIVEN_no_driving_dataset_selected_for_model_WHEN_page_get_THEN_redirect_to_driving_data(self):
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        with session_scope(Session) as session:
            model_run.driving_dataset_id = None
            session.add(model_run)
        response = self.app.get(
            url(controller='model_run', action='extents'))
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='driving_data')), "url")

    def test_GIVEN_nothing_WHEN_page_get_THEN_extents_page_rendered(self):
        response = self.app.get(
            url(controller='model_run', action='extents'))
        assert_that(response.normal_body, contains_string("Specify Model Run Extents"))
        self.assert_model_run_creation_action(self.user, 'extents')

    def test_GIVEN_driving_dataset_selected_for_model_WHEN_page_get_THEN_driving_data_spatial_extents_rendered(self):
        response = self.app.get(
            url(controller='model_run', action='extents'))
        assert_that(response.normal_body, contains_string(str(self.driving_data.boundary_lat_north)))
        assert_that(response.normal_body, contains_string(str(self.driving_data.boundary_lat_south)))
        assert_that(response.normal_body, contains_string(str(self.driving_data.boundary_lon_east)))
        assert_that(response.normal_body, contains_string(str(self.driving_data.boundary_lon_west)))

    def test_GIVEN_driving_dataset_selected_for_model_WHEN_page_get_THEN_driving_data_temporal_extents_rendered(self):
        response = self.app.get(
            url(controller='model_run', action='extents'))
        assert_that(response.normal_body, contains_string("1901-01-01"))
        assert_that(response.normal_body, contains_string("1911-01-01"))

    def test_GIVEN_multi_cell_spatial_extents_already_chosen_WHEN_page_get_THEN_existing_extents_rendered(self):
        self.model_run_service.save_parameter(JULES_PARAM_LON_BOUNDS, [12.3, 35.5], self.user)
        self.model_run_service.save_parameter(JULES_PARAM_LAT_BOUNDS, [50, 70], self.user)
        self.model_run_service.save_parameter(JULES_PARAM_USE_SUBGRID, True, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_LATLON_REGION, True, self.user)
        response = self.app.get(
            url(controller='model_run', action='extents'))
        assert_that(response.normal_body, contains_string("12.3"))
        assert_that(response.normal_body, contains_string("35.5"))
        assert_that(response.normal_body, contains_string("50"))
        assert_that(response.normal_body, contains_string("70"))

    def test_GIVEN_single_cell_spatial_extents_already_chosen_WHEN_page_get_THEN_existing_extents_rendered(self):
        self.model_run_service.save_parameter(JULES_PARAM_USE_SUBGRID, True, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_LATLON_REGION, False, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_NPOINTS, 1, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_POINTS_FILE, [55, 12.3], self.user)
        response = self.app.get(
            url(controller='model_run', action='extents'))
        assert_that(response.normal_body, contains_string("55"))
        assert_that(response.normal_body, contains_string("12.3"))

    def test_GIVEN_temporal_extents_already_chosen_WHEN_page_get_THEN_existing_extents_rendered(self):
        self.model_run_service.save_parameter(JULES_PARAM_LON_BOUNDS, [12.3, 35.5], self.user)
        self.model_run_service.save_parameter(JULES_PARAM_LAT_BOUNDS, [50, 70], self.user)
        self.model_run_service.save_parameter(JULES_PARAM_USE_SUBGRID, True, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_LATLON_REGION, True, self.user)
        start_time = datetime.datetime(1935, 3, 5, 17, 12, 11)
        end_time = datetime.datetime(1969, 7, 21, 20, 17, 00)
        self.model_run_service.save_parameter(JULES_PARAM_RUN_START, start_time, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_RUN_END, end_time, self.user)
        response = self.app.get(
            url(controller='model_run', action='extents'))
        assert_that(response.normal_body, contains_string(start_time.strftime("%Y-%m-%d")))
        assert_that(response.normal_body, contains_string(end_time.strftime("%Y-%m-%d")))

    def test_GIVEN_invalid_multi_cell_spatial_extents_already_chosen_WHEN_page_get_THEN_errors_shown(self):
        self.model_run_service.save_parameter(JULES_PARAM_LON_BOUNDS, [40, 500], self.user)
        self.model_run_service.save_parameter(JULES_PARAM_LAT_BOUNDS, [20, 25], self.user)
        self.model_run_service.save_parameter(JULES_PARAM_USE_SUBGRID, True, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_LATLON_REGION, True, self.user)
        response = self.app.get(
            url(controller='model_run', action='extents'))
        assert_that(response.normal_body, contains_string("Longitude must be between -180 and 180"))

    def test_GIVEN_invalid_single_cell_spatial_extents_already_chosen_WHEN_page_get_THEN_errors_shown(self):
        self.model_run_service.save_parameter(JULES_PARAM_USE_SUBGRID, True, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_LATLON_REGION, False, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_NPOINTS, 1, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_POINTS_FILE, [55, 593], self.user)
        response = self.app.get(
            url(controller='model_run', action='extents'))
        assert_that(response.normal_body, contains_string("Longitude must be between -180 and 180"))

    def test_GIVEN_invalid_temporal_extents_already_chosen_WHEN_page_get_THEN_errors_shown(self):
        self.model_run_service.save_parameter(JULES_PARAM_LON_BOUNDS, [12.3, 35.5], self.user)
        self.model_run_service.save_parameter(JULES_PARAM_LAT_BOUNDS, [50, 70], self.user)
        self.model_run_service.save_parameter(JULES_PARAM_USE_SUBGRID, True, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_LATLON_REGION, True, self.user)
        start_time = datetime.datetime(1900, 10, 14, 17, 12, 11)
        end_time = datetime.datetime(1969, 7, 21, 20, 17, 00)
        self.model_run_service.save_parameter(JULES_PARAM_RUN_START, start_time, self.user)
        self.model_run_service.save_parameter(JULES_PARAM_RUN_END, end_time, self.user)
        response = self.app.get(
            url(controller='model_run', action='extents'))
        assert_that(response.normal_body, contains_string("Start date cannot be earlier than 1901-01-01"))

    def test_GIVEN_invalid_multi_cell_spatial_extents_WHEN_post_THEN_errors_rendered(self):
        response = self.app.post(
            url(controller='model_run', action='extents'),
            params={
                'submit': u'Next',
                'site': u'multi',
                'lat_n': 25,
                'lat_s': 20,
                'lon_e': 40,
                'lon_w': 500,
                'start_date': '1940-10-13',
                'end_date': '1950-10-13'
            })
        assert_that(response.normal_body, contains_string("Longitude must be between -180 and 180"))

    def test_GIVEN_invalid_single_cell_spatial_extents_WHEN_post_THEN_errors_rendered(self):
        response = self.app.post(
            url(controller='model_run', action='extents'),
            params={
                'submit': u'Next',
                'site': u'single',
                'lat': -88,
                'lon': 40,
                'start_date': '1940-10-13',
                'end_date': '1950-10-13'
            })
        assert_that(response.normal_body, contains_string("Latitude (-88 deg N) cannot be south of 13.8 deg N"))

    def test_GIVEN_invalid_temporal_extents_WHEN_post_THEN_errors_rendered(self):
        response = self.app.post(
            url(controller='model_run', action='extents'),
            params={
                'submit': u'Next',
                'site': u'multi',
                'lat_n': 25,
                'lat_s': 20,
                'lon_e': 40,
                'lon_w': 35,
                'start_date': '1900-10-14',
                'end_date': '1950-10-13'
            })
        assert_that(response.normal_body, contains_string("Start date cannot be earlier than 1901-01-01"))

    def test_GIVEN_valid_multi_cell_extents_WHEN_post_THEN_extents_saved(self):
        self.app.post(
            url(controller='model_run', action='extents'),
            params={
                'submit': u'Next',
                'site': u'multi',
                'lat_n': 25,
                'lat_s': 20,
                'lon_e': 40,
                'lon_w': 35,
                'start_date': '1940-10-13',
                'end_date': '1950-10-13'
            })
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        lat_bounds = model_run.get_parameter_values(JULES_PARAM_LAT_BOUNDS)[0].value
        lon_bounds = model_run.get_parameter_values(JULES_PARAM_LON_BOUNDS)[0].value
        use_subgrid = model_run.get_parameter_values(JULES_PARAM_USE_SUBGRID)[0].value
        latlon_region = model_run.get_parameter_values(JULES_PARAM_LATLON_REGION)[0].value
        start_run = model_run.get_parameter_values(JULES_PARAM_RUN_START)[0].value
        end_run = model_run.get_parameter_values(JULES_PARAM_RUN_END)[0].value
        assert_that(lat_bounds, is_("20    25"))
        assert_that(lon_bounds, is_("35    40"))
        assert_that(use_subgrid, is_(".true."))
        assert_that(latlon_region, is_(".true."))
        assert_that(str(start_run), is_("'1940-10-13 00:00:00'"))
        assert_that(str(end_run), is_("'1950-10-13 23:00:00'"))  # Time is moved forward to match the acceptable end

    def test_GIVEN_valid_single_cell_extents_WHEN_post_THEN_extents_saved(self):
        self.set_up_single_cell_user_driving_data()
        self.app.post(
            url(controller='model_run', action='extents'),
            params={
                'submit': u'Next',
                'site': u'single',
                'lat': 25,
                'lon': 40,
                'start_date': '1901-01-4',
                'end_date': '1901-01-13',
                'average_over_cell': 1
            })
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        pointfile = model_run.get_parameter_values(JULES_PARAM_POINTS_FILE)[0].value
        n_points = model_run.get_parameter_values(JULES_PARAM_NPOINTS)[0].value
        use_subgrid = model_run.get_parameter_values(JULES_PARAM_USE_SUBGRID)[0].value
        latlon_region = model_run.get_parameter_values(JULES_PARAM_LATLON_REGION)[0].value
        l_point_data = model_run.get_parameter_values(JULES_PARAM_SWITCHES_L_POINT_DATA)[0].value
        start_run = model_run.get_parameter_values(JULES_PARAM_RUN_START)[0].value
        end_run = model_run.get_parameter_values(JULES_PARAM_RUN_END)[0].value
        assert_that(pointfile, is_("25    40"))
        assert_that(n_points, is_("1"))
        assert_that(use_subgrid, is_(".true."))
        assert_that(latlon_region, is_(".false."))
        assert_that(l_point_data, is_(".false."))
        assert_that(str(start_run), is_("'1901-01-04 00:00:00'"))
        assert_that(str(end_run), is_("'1901-01-13 20:00:00'"))  # Interpolation flag brings us forward an hour

    def test_GIVEN_valid_extents_WHEN_post_THEN_redirect_to_output(self):
        response = self.app.post(
            url(controller='model_run', action='extents'),
            params={
                'submit': u'Next',
                'site': u'multi',
                'lat_n': 25,
                'lat_s': 20,
                'lon_e': 40,
                'lon_w': 35,
                'start_date': '1940-10-13',
                'end_date': '1950-10-13'
            })
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='land_cover')), "url")

    def test_GIVEN_valid_extents_and_user_over_quota_WHEN_post_THEN_redirect_to_catalogue(self):
        self.create_run_model(storage_in_mb=self.user.storage_quota_in_gb * 1024 + 1, name="big_run", user=self.user)

        response = self.app.post(
            url(controller='model_run', action='extents'),
            params={
                'submit': u'Next',
                'site': u'multi',
                'lat_n': 25,
                'lat_s': 20,
                'lon_e': 40,
                'lon_w': 35,
                'start_date': '1940-10-13',
                'end_date': '1950-10-13'
            })
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='index')), "url")

    def test_GIVEN_bng_WHEN_bng_to_latlon_service_called_THEN_correct_latlon_returned(self):
        # BNG test values are from http://www.bgs.ac.uk/data/webservices/convertForm.cfm
        bng_easting = 429157
        bng_northing = 623009
        lat = 55.5
        lon = -1.54
        delta = 0.00001
        response = self.app.post(
            url(controller='model_run', action='bng_to_latlon'),
            params={
                'bng_easting': bng_easting,
                'bng_northing': bng_northing
            })
        json = response.json_body
        assert_that(json['lat'], is_(close_to(lat, delta)))
        assert_that(json['lon'], is_(close_to(lon, delta)))

    def test_GIVEN_invalid_bng_WHEN_bng_to_latlon_service_called_THEN_error_returned(self):
        response = self.app.post(
            url(controller='model_run', action='bng_to_latlon'),
            params={
                'bng_easting': u'asd',
                'bng_northing': u'1.1,23413'
            })
        json = response.json_body
        assert_that(json['is_error'], is_(True))
class TestModelRunLandCoverSingleCell(TestController):
    def setUp(self):
        self.model_run_service = ModelRunService()
        self.land_cover_service = LandCoverService()

    def set_up_single_cell_model_run(self):
        self.clean_database()
        self.user = self.login()
        self.create_two_driving_datasets()
        user_upload_id = DatasetService().get_id_for_user_upload_driving_dataset()
        with session_scope(Session) as session:
            self.model_run = ModelRun()
            self.model_run.name = "MR1"
            self.model_run.status = self._status(MODEL_RUN_STATUS_CREATED)
            self.model_run.driving_dataset_id = user_upload_id
            self.model_run.user = self.user
            self.model_run.driving_data_lat = 51.75
            self.model_run.driving_data_lon = -0.25
            self.model_run.driving_data_rows = 248

            param1 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_DRIVE_INTERP)
            pv1 = ParameterValue()
            pv1.parameter_id = param1.id
            pv1.set_value_from_python(8 * ['nf'])

            param2 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_DRIVE_DATA_PERIOD)
            pv2 = ParameterValue()
            pv2.parameter_id = param2.id
            pv2.set_value_from_python(60 * 60)

            param3 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_DRIVE_DATA_START)
            pv3 = ParameterValue()
            pv3.parameter_id = param3.id
            pv3.value = "'1901-01-01 00:00:00'"

            param4 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_DRIVE_DATA_END)
            pv4 = ParameterValue()
            pv4.parameter_id = param4.id
            pv4.value = "'1901-01-31 21:00:00'"

            param5 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_LATLON_REGION)
            pv5 = ParameterValue()
            pv5.parameter_id = param5.id
            pv5.value = ".false."

            param6 = self.model_run_service.get_parameter_by_constant(JULES_PARAM_POINTS_FILE)
            pv6 = ParameterValue()
            pv6.parameter_id = param6.id
            pv6.value = "51.75 -0.25"

            self.model_run.parameter_values = [pv1, pv2, pv3, pv4, pv5, pv6]
            session.add(self.model_run)

    def test_GIVEN_single_cell_run_WHEN_page_get_THEN_fractional_cover_page_shown(self):
        self.set_up_single_cell_model_run()
        response = self.app.get(url(controller='model_run', action='land_cover'))
        assert_that(response.normal_body, contains_string("Fractional Land Cover"))

    def test_GIVEN_land_cover_values_WHEN_page_get_THEN_land_cover_type_names_rendered(self):
        self.set_up_single_cell_model_run()
        response = self.app.get(url(controller='model_run', action='land_cover'))
        lc_vals = self.land_cover_service.get_land_cover_values(None)
        del lc_vals[-1]  # Remove the ice
        names = [str(val.name) for val in lc_vals]
        assert_that(response.normal_body, string_contains_in_order(*names))

    def test_GIVEN_available_driving_datasets_WHEN_page_get_THEN_default_fractional_cover_rendered(self):
        self.set_up_single_cell_model_run()
        response = self.app.get(url(controller='model_run', action='land_cover'))
        lc_vals = self.land_cover_service.get_land_cover_values(None)
        del lc_vals[-1]  # Remove the ice
        string_names_values = []
        for val in lc_vals:
            string_names_values.append(str(val.name))
            string_names_values.append('12.5')
        assert_that(response.normal_body, string_contains_in_order(*string_names_values))

    def test_GIVEN_saved_land_cover_frac_WHEN_page_get_THEN_saved_values_rendered(self):
        self.set_up_single_cell_model_run()
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        frac_string = "0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.72 0.0"
        self.land_cover_service.save_fractional_land_cover_for_model(model_run, frac_string)

        response = self.app.get(url(controller='model_run', action='land_cover'))

        lc_vals = self.land_cover_service.get_land_cover_values(None)
        del lc_vals[-1]  # Remove the ice

        string_names_values = []
        for i in range(len(lc_vals)):
            string_names_values.append(str(lc_vals[i].name))
            string_names_values.append(str(100 * float(frac_string.split()[i])))
        assert_that(response.normal_body, string_contains_in_order(*string_names_values))

    def test_GIVEN_saved_land_cover_with_too_few_types_WHEN_page_get_THEN_available_values_rendered(self):
        self.set_up_single_cell_model_run()
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        frac_string = "0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.72"
        self.land_cover_service.save_fractional_land_cover_for_model(model_run, frac_string)

        response = self.app.get(url(controller='model_run', action='land_cover'))

        lc_vals = self.land_cover_service.get_land_cover_values(None)
        del lc_vals[-1]  # Remove the ice

        string_names_values = []
        for i in range(len(lc_vals)):
            string_names_values.append(str(lc_vals[i].name))
            string_names_values.append(str(100 * float(frac_string.split()[i])))
        assert_that(response.normal_body, string_contains_in_order(*string_names_values))

    def test_GIVEN_saved_land_cover_with_too_many_types_WHEN_page_get_THEN_some_values_rendered(self):
        self.set_up_single_cell_model_run()
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        frac_string = "0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.72 0.0 0.0"
        self.land_cover_service.save_fractional_land_cover_for_model(model_run, frac_string)

        response = self.app.get(url(controller='model_run', action='land_cover'))

        lc_vals = self.land_cover_service.get_land_cover_values(None)
        del lc_vals[-1]  # Remove the ice

        string_names_values = []
        for i in range(len(lc_vals)):
            string_names_values.append(str(lc_vals[i].name))
            string_names_values.append(str(100 * float(frac_string.split()[i])))
        assert_that(response.normal_body, string_contains_in_order(*string_names_values))

    def test_GIVEN_valid_fractional_cover_WHEN_post_THEN_values_saved(self):
        self.set_up_single_cell_model_run()
        self.app.post(
            url(controller='model_run', action='land_cover'),
            params={'submit': u'Next',
                    'fractional_cover': u'1',
                    'land_cover_value_1': u'20',
                    'land_cover_value_2': u'25',
                    'land_cover_value_3': u'5',
                    'land_cover_value_4': u'10',
                    'land_cover_value_5': u'10',
                    'land_cover_value_6': u'5',
                    'land_cover_value_7': u'10',
                    'land_cover_value_8': u'15'})
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        assert_that(model_run.land_cover_frac, is_("0.2\t0.25\t0.05\t0.1\t0.1\t0.05\t0.1\t0.15\t0"))

    def test_GIVEN_valid_fractional_cover_WHEN_post_THEN_default_soil_props_saved(self):
        self.set_up_single_cell_model_run()
        self.app.post(
            url(controller='model_run', action='land_cover'),
            params={'submit': u'Next',
                    'fractional_cover': u'1',
                    'land_cover_value_1': u'20',
                    'land_cover_value_2': u'25',
                    'land_cover_value_3': u'5',
                    'land_cover_value_4': u'10',
                    'land_cover_value_5': u'10',
                    'land_cover_value_6': u'5',
                    'land_cover_value_7': u'10',
                    'land_cover_value_8': u'15'})
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        soil_props = model_run.get_python_parameter_value(JULES_PARAM_SOIL_PROPS_CONST_VAL, is_list=True)
        assert_that(soil_props, is_([0.9, 0.0, 0.0, 50.0, 275.0, 300.0, 10.0, 0.0, 0.5]))

    def test_GIVEN_ice_fractional_cover_WHEN_post_THEN_values_saved(self):
        self.set_up_single_cell_model_run()
        self.app.post(
            url(controller='model_run', action='land_cover'),
            params={'submit': u'Next',
                    'fractional_cover': u'1',
                    'land_cover_ice': u'1'})
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        assert_that(model_run.land_cover_frac, is_("0\t0\t0\t0\t0\t0\t0\t0\t1"))

    def test_GIVEN_valid_fractional_cover_WHEN_post_THEN_moved_to_next_page(self):
        self.set_up_single_cell_model_run()
        response = self.app.post(
            url(controller='model_run', action='land_cover'),
            params={'submit': u'Next',
                    'fractional_cover': u'1',
                    'land_cover_value_1': u'20',
                    'land_cover_value_2': u'25',
                    'land_cover_value_3': u'5',
                    'land_cover_value_4': u'10',
                    'land_cover_value_5': u'10',
                    'land_cover_value_6': u'5',
                    'land_cover_value_7': u'10',
                    'land_cover_value_8': u'15'})
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='output')), "url")

    def test_GIVEN_fractional_cover_saved_WHEN_reset_THEN_cover_reset(self):
        self.set_up_single_cell_model_run()
        self.app.post(
            url(controller='model_run', action='land_cover'),
            params={'submit': u'Next',
                    'fractional_cover': u'1',
                    'land_cover_value_1': u'20',
                    'land_cover_value_2': u'25',
                    'land_cover_value_3': u'5',
                    'land_cover_value_4': u'10',
                    'land_cover_value_5': u'10',
                    'land_cover_value_6': u'5',
                    'land_cover_value_7': u'10',
                    'land_cover_value_8': u'15'})
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        initial_cover = model_run.land_cover_frac
        assert initial_cover is not None
        response = self.app.post(
            url(controller='model_run', action='land_cover'),
            params={'reset_fractional_cover': u'1'})
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='land_cover')), "url")
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        final_cover = model_run.land_cover_frac
        assert_that(final_cover, is_(None))

    def test_GIVEN_values_dont_add_up_WHEN_post_THEN_errors_returned_and_values_not_saved(self):
        self.set_up_single_cell_model_run()
        response = self.app.post(
            url(controller='model_run', action='land_cover'),
            params={'submit': u'Next',
                    'fractional_cover': u'1',
                    'land_cover_value_1': u'40',
                    'land_cover_value_2': u'25',
                    'land_cover_value_3': u'5',
                    'land_cover_value_4': u'10',
                    'land_cover_value_5': u'10',
                    'land_cover_value_6': u'5',
                    'land_cover_value_7': u'10',
                    'land_cover_value_8': u'15'})
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        assert_that(model_run.land_cover_frac, is_(None))
        assert_that(response.normal_body, contains_string("The sum of all the land cover fractions must be 100%"))
        assert_that(response.normal_body, contains_string("Fractional Land Cover"))

    def test_GIVEN_values_dont_add_up_WHEN_post_THEN_values_still_present_on_page(self):
        self.set_up_single_cell_model_run()
        response = self.app.post(
            url(controller='model_run', action='land_cover'),
            params={'submit': u'Next',
                    'fractional_cover': u'1',
                    'land_cover_value_1': u'40',
                    'land_cover_value_2': u'25',
                    'land_cover_value_3': u'5',
                    'land_cover_value_4': u'10',
                    'land_cover_value_5': u'10',
                    'land_cover_value_6': u'5',
                    'land_cover_value_7': u'10',
                    'land_cover_value_8': u'15'})

        lc_vals = self.land_cover_service.get_land_cover_values(None)
        del lc_vals[-1]  # Remove the ice
        frac_vals = ['40', '25', '5', '10', '10', '5', '10', '15']
        string_names_values = []
        for i in range(len(lc_vals)):
            string_names_values.append(str(lc_vals[i].name))
            string_names_values.append(str(frac_vals[i]))
        assert_that(response.normal_body, string_contains_in_order(*string_names_values))

    def test_GIVEN_no_extents_selected_WHEN_page_get_THEN_redirect(self):
        self.set_up_single_cell_model_run()
        param = self.model_run_service.get_parameter_by_constant(JULES_PARAM_POINTS_FILE)
        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)
        with session_scope() as session:
            session.query(ParameterValue) \
                .filter(ParameterValue.parameter_id == param.id) \
                .filter(ParameterValue.model_run_id == model_run.id) \
                .delete()

        response = self.app.get(url(controller='model_run', action='land_cover'))
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='extents')), "url")
class TestModelRunLandCover(TestController):
    def setUp(self):
        self.clean_database()
        self.user = self.login()
        self.create_two_driving_datasets()
        dds = DatasetService().get_driving_datasets(self.user)[0]
        with session_scope() as session:
            model_run = ModelRun()
            model_run.name = "model run"
            model_run.change_status(session, MODEL_RUN_STATUS_CREATED)
            model_run.user = self.user
            model_run.driving_dataset_id = dds.id
            session.add(model_run)
            session.commit()

            self.model_run_service = ModelRunService()
            model_run = self.model_run_service._get_model_run_being_created(session, self.user)

            parameter_val = ParameterValue()
            parameter_val.parameter = self.model_run_service.get_parameter_by_constant(JULES_PARAM_LATLON_REGION)
            parameter_val.set_value_from_python(True)
            parameter_val.model_run_id = model_run.id
            session.add(parameter_val)

        self.add_land_cover_region(model_run)

    def test_GIVEN_land_cover_actions_WHEN_post_THEN_land_cover_action_saved_in_database(self):
        with session_scope() as session:
            model_run = self.model_run_service._get_model_run_being_created(session, self.user)
            dds = model_run.driving_dataset
        categories = LandCoverService().get_land_cover_categories(dds.id)
        # Need to know the region IDs
        self.app.post(
            url(controller='model_run', action='land_cover'),
            params={
                'submit': u'Next',
                'action_1_region': str(categories[0].regions[0].id),
                'action_1_value': u'8',
                'action_1_order': u'1',
                'action_2_region': str(categories[0].regions[0].id),
                'action_2_value': u'7',
                'action_2_order': u'2'
            })
        with session_scope() as session:
            model_run = self.model_run_service._get_model_run_being_created(session, self.user)

        actions = model_run.land_cover_actions
        assert_that(len(actions), is_(2))
        for action in actions:
            if action.value_id == 8:
                assert_that(action.order, is_(1))
            elif action.value_id == 7:
                assert_that(action.order, is_(2))
            else:
                assert False

    def test_GIVEN_invalid_land_cover_actions_WHEN_post_THEN_error_shown_and_stay_on_page(self):
        # Add some regions to another driving dataset
        dds = DatasetService().get_driving_datasets(self.user)[1]
        with session_scope() as session:
            land_cat = LandCoverRegionCategory()
            land_cat.driving_dataset = dds
            land_cat.name = "Category2"

            land_region = LandCoverRegion()
            land_region.name = "Region1"
            land_region.category = land_cat
            session.add(land_region)

        response = self.app.post(
            url(controller='model_run', action='land_cover'),
            params={
                'submit': u'Next',
                'action_1_region': str(land_region.id),
                'action_1_value': u'8',
                'action_1_order': u'1'
            })
        assert_that(response.normal_body, contains_string("Land Cover"))  # Check still on page
        assert_that(response.normal_body, contains_string("Land Cover Region not valid for the chosen driving data"))

    def test_GIVEN_land_cover_values_and_regions_exist_WHEN_get_THEN_regions_and_categories_rendered(self):
        with session_scope() as session:
            model_run = self.model_run_service._get_model_run_being_created(session, self.user)
            dds = model_run.driving_dataset
            session.add_all(self.generate_categories_with_regions(dds))

        response = self.app.get(url(controller='model_run', action='land_cover'))

        assert_that(response.normal_body, contains_string("Rivers"))
        assert_that(response.normal_body, contains_string("Thames"))
        assert_that(response.normal_body, contains_string("Itchen"))
        assert_that(response.normal_body, contains_string("Counties"))
        assert_that(response.normal_body, contains_string("Hampshire"))
        assert_that(response.normal_body, contains_string("Oxfordshire"))

    def test_GIVEN_nothing_WHEN_get_THEN_values_rendered(self):
        response = self.app.get(url(controller='model_run', action='land_cover'))

        values = LandCoverService().get_land_cover_values(None, return_ice=False)
        for value in values:
            assert_that(response.normal_body, contains_string(str(value.name)))

    def test_GIVEN_land_cover_action_already_saved_WHEN_get_THEN_action_rendered(self):
        with session_scope() as session:
            model_run = self.model_run_service._get_model_run_being_created(session, self.user)
            dds = model_run.driving_dataset
            session.add_all(self.generate_categories_with_regions(dds))

            action = LandCoverAction()
            action.model_run = model_run
            action.region_id = 1  # Thames
            action.value_id = 5  # Shrub

        response = self.app.get(url(controller='model_run', action='land_cover'))
        assert_that(response.normal_body, contains_string("Change <b>Thames (Rivers)</b> to <b>Shrub</b>"))

    def test_GIVEN_invalid_land_cover_actions_already_saved_WHEN_get_THEN_errors_returned_no_actions_rendered(self):
        with session_scope() as session:
            model_run = self.model_run_service._get_model_run_being_created(session, self.user)
            dds = model_run.driving_dataset
            session.add_all(self.generate_categories_with_regions(dds))

            action = LandCoverAction()
            action.model_run = model_run
            action.region_id = 1  # Thames
            action.value_id = 9  # Ice
            session.add(action)
            session.commit()

            # Set the model run to have a different driving dataset - this should result in an error
            model_run.driving_dataset = session.query(DrivingDataset).filter(DrivingDataset.name == "driving2").one()

        response = self.app.get(url(controller='model_run', action='land_cover'))
        assert_that(response.normal_body, contains_string("Your saved Land Cover edits are not valid for the "
                                                          "chosen driving data"))
        assert_that(response.normal_body, is_not(contains_string("Change <b>")))  # Actions start with this

    def test_GIVEN_multiple_land_cover_actions_saved_out_of_order_WHEN_get_THEN_order_rendered_correctly(self):
        with session_scope() as session:
            model_run = self.model_run_service._get_model_run_being_created(session, self.user)
            dds = model_run.driving_dataset
            session.add_all(self.generate_categories_with_regions(dds))

            action = LandCoverAction()
            action.model_run = model_run
            action.region_id = 1  # Thames
            action.value_id = 5  # Shrub
            action.order = 5
            session.add(action)
            session.commit()

            action2 = LandCoverAction()
            action2.model_run = model_run
            action2.region_id = 2  # Itchen
            action2.value_id = 1  # Broad-leaved Tree
            action2.order = 1
            session.add(action2)
            session.commit()

            action3 = LandCoverAction()
            action3.model_run = model_run
            action3.region_id = 3  # Hampshire
            action3.value_id = 6  # Urban
            action3.order = 2
            session.add(action3)
            session.commit()

        response = self.app.get(url(controller='model_run', action='land_cover'))
        order1 = response.normal_body.index("Change <b>Itchen (Rivers)</b> to <b>Broad-leaved Tree</b>")
        order2 = response.normal_body.index("Change <b>Hampshire (Counties)</b> to <b>Urban</b>")
        order5 = response.normal_body.index("Change <b>Thames (Rivers)</b> to <b>Shrub</b>")
        assert (order1 < order2 < order5)

    def generate_categories_with_regions(self, driving_dataset):
        # Add categories
        cat1 = LandCoverRegionCategory()
        cat1.driving_dataset_id = driving_dataset.id
        cat1.name = "Rivers"
        cat1.id = 1

        region1 = LandCoverRegion()
        region1.id = 1
        region1.name = "Thames"
        region1.category_id = 1
        region1.category = cat1

        region2 = LandCoverRegion()
        region2.id = 2
        region2.name = "Itchen"
        region2.category_id = 1
        region2.category = cat1

        cat1.regions = [region1, region2]

        cat2 = LandCoverRegionCategory()
        cat2.driving_dataset_id = driving_dataset.id
        cat2.name = "Counties"
        cat2.id = 2

        region3 = LandCoverRegion()
        region3.id = 3
        region3.name = "Hampshire"
        region3.category_id = 2
        region3.category = cat2

        region4 = LandCoverRegion()
        region4.id = 4
        region4.name = "Oxfordshire"
        region4.category_id = 2
        region4.category = cat2

        cat2.regions = [region3, region4]

        return [cat1, cat2]
class TestModelRunOutput(TestController):
    def setUp(self):
        super(TestModelRunOutput, self).setUp()
        self.clean_database()
        self.user = self.login()
        self.valid_params = {
            'submit': u'Next',
            'ov_select_1': 1,
            'ov_yearly_1': 1,
            'ov_monthly_1': 1,
            'ov_select_2': 1,
            'ov_hourly_2': 1,
            'ov_daily_2': 1,
            'ov_select_3': 1,
            'ov_monthly_3': 1
        }
        self.model_run_service = ModelRunService()
        param_run_start = self.model_run_service.get_parameter_by_constant(JULES_PARAM_RUN_START)
        param_run_end = self.model_run_service.get_parameter_by_constant(JULES_PARAM_RUN_END)
        with session_scope(Session) as session:
            self.model_run = self.model_run_service._create_new_model_run(session, self.user)
            self.model_run.name = "MR1"

            pv_run_start = ParameterValue()
            pv_run_start.parameter_id = param_run_start.id
            pv_run_start.value = "'1901-01-01 00:00:00'"

            pv_run_end = ParameterValue()
            pv_run_end.parameter_id = param_run_end.id
            pv_run_end.value = "'1902-01-01 00:00:00'"

            self.model_run.parameter_values = [pv_run_start, pv_run_end]

            session.add(self.model_run)

    def test_GIVEN_no_model_being_created_WHEN_page_get_THEN_redirect_to_create_model_run(self):
        self.clean_database()
        self.user = self.login()
        response = self.app.get(
            url(controller='model_run', action='output'))
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path, is_(url(controller='model_run', action='create')), "url")

    def test_GIVEN_model_run_created_WHEN_page_get_THEN_page_loaded(self):
        response = self.app.get(
            url(controller='model_run', action='output'))
        assert_that(response.normal_body, contains_string("Select Output Variables"))
        self.assert_model_run_creation_action(self.user, 'output')

    def test_GIVEN_output_parameters_already_chosen_WHEN_page_get_THEN_parameters_rendered(self):
        self.app.post(
            url(controller='model_run', action='output'),
            params=self.valid_params)
        response = self.app.get(url(controller='model_run', action='output'))
        doc = html.fromstring(response.normal_body)
        
        # Check that the first output variable is displayed, selected and the yearly and monthly period boxes selected:
        output_row_1 = doc.xpath('//div[@id="output_row_1"]/@style')
        assert_that(output_row_1, is_not(contains_string('display:none')))
        ov_select_1 = doc.xpath('//input[@name="ov_select_1"]/@checked')
        ov_yearly_1 = doc.xpath('//input[@name="ov_yearly_1"]/@checked')
        ov_monthly_1 = doc.xpath('//input[@name="ov_monthly_1"]/@checked')
        ov_daily_1 = doc.xpath('//input[@name="ov_daily_1"]/@checked')
        ov_hourly_1 = doc.xpath('//input[@name="ov_hourly_1"]/@checked')
        assert_that(len(ov_select_1), is_(1))
        assert_that(len(ov_yearly_1), is_(1))
        assert_that(len(ov_monthly_1), is_(1))
        assert_that(len(ov_daily_1), is_(0))
        assert_that(len(ov_hourly_1), is_(0))
        
        # For the second we expect the same but with the hourly period box selected
        output_row_2 = doc.xpath('//div[@id="output_row_2"]/@style')
        assert_that(output_row_2, is_not(contains_string('display:none')))
        ov_select_2 = doc.xpath('//input[@name="ov_select_2"]/@checked')
        ov_yearly_2 = doc.xpath('//input[@name="ov_yearly_2"]/@checked')
        ov_monthly_2 = doc.xpath('//input[@name="ov_monthly_2"]/@checked')
        ov_daily_2 = doc.xpath('//input[@name="ov_daily_2"]/@checked')
        ov_hourly_2 = doc.xpath('//input[@name="ov_hourly_2"]/@checked')
        assert_that(len(ov_select_2), is_(1))
        assert_that(len(ov_yearly_2), is_(0))
        assert_that(len(ov_monthly_2), is_(0))
        assert_that(len(ov_daily_2), is_(1))
        assert_that(len(ov_hourly_2), is_(1))
        
        # For the third we expect the monthly box selected
        output_row_3 = doc.xpath('//div[@id="output_row_3"]/@style')
        assert_that(output_row_3, is_not(contains_string('display:none')))
        ov_select_3 = doc.xpath('//input[@name="ov_select_3"]/@checked')
        ov_yearly_3 = doc.xpath('//input[@name="ov_yearly_3"]/@checked')
        ov_monthly_3 = doc.xpath('//input[@name="ov_monthly_3"]/@checked')
        ov_daily_3 = doc.xpath('//input[@name="ov_daily_3"]/@checked')
        ov_hourly_3 = doc.xpath('//input[@name="ov_hourly_3"]/@checked')
        assert_that(len(ov_select_3), is_(1))
        assert_that(len(ov_yearly_3), is_(0))
        assert_that(len(ov_monthly_3), is_(1))
        assert_that(len(ov_daily_3), is_(0))
        assert_that(len(ov_hourly_3), is_(0))
        
        # Finally we check that no other output parameters are selected or visible
        ov_selects = doc.xpath('//input[contains(@name, "ov_select_") and not(@checked)]')
        n_output_params = len(self.model_run_service.get_output_variables(include_depends_on_nsmax=False))
        assert_that(len(ov_selects), is_(n_output_params - 3))

        invisible_rows = doc.xpath('//div[contains(@id, "output_row_") and contains(@style, "display:none")]')
        assert_that(len(invisible_rows), is_(n_output_params - 3))

    def test_GIVEN_selected_outputs_WHEN_post_THEN_redirected_to_next_page(self):
        response = self.app.post(
            url(controller='model_run', action='output'),
            params=self.valid_params)
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='submit')), "url")

    def test_GIVEN_selected_outputs_and_user_over_quota_WHEN_post_THEN_redirected_to_catalogue(self):
        self.create_run_model(storage_in_mb=self.user.storage_quota_in_gb * 1024 + 1, name="big_run", user=self.user)
        response = self.app.post(
            url(controller='model_run', action='output'),
            params=self.valid_params)
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='index')), "url")

    def test_GIVEN_selected_outputs_WHEN_post_THEN_params_stored_in_database(self):
        self.app.post(
            url(controller='model_run', action='output'),
            params=self.valid_params)

        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)

        # Check we have the right number of profiles
        n_expected = 5
        p_output_nprofiles = model_run.get_parameter_values(JULES_PARAM_OUTPUT_NPROFILES)[0].get_value_as_python()
        assert_that(p_output_nprofiles, is_(n_expected))

        pv_var = model_run.get_parameter_values(JULES_PARAM_OUTPUT_VAR)
        pv_nvars = model_run.get_parameter_values(JULES_PARAM_OUTPUT_NVARS)
        pv_profile_name = model_run.get_parameter_values(JULES_PARAM_OUTPUT_PROFILE_NAME)
        pv_output_main_run = model_run.get_parameter_values(JULES_PARAM_OUTPUT_MAIN_RUN)
        pv_output_period = model_run.get_parameter_values(JULES_PARAM_OUTPUT_PERIOD)
        pv_output_types = model_run.get_parameter_values(JULES_PARAM_OUTPUT_TYPE)

        # Check they are all 5
        assert_that(len(pv_var), is_(n_expected))
        assert_that(len(pv_nvars), is_(n_expected))
        assert_that(len(pv_profile_name), is_(n_expected))
        assert_that(len(pv_output_main_run), is_(n_expected))
        assert_that(len(pv_output_period), is_(n_expected))
        assert_that(len(pv_output_types), is_(n_expected))

        # Create list of values so we can check they are correct (easier than checking ParameterValue objects)
        var_vals = [pv.get_value_as_python() for pv in pv_var]
        nvars_vals = [pv.get_value_as_python() for pv in pv_nvars]
        profile_name_vals = [pv.get_value_as_python() for pv in pv_profile_name]
        output_main_run_vals = [pv.get_value_as_python() for pv in pv_output_main_run]
        output_period_vals = [pv.get_value_as_python() for pv in pv_output_period]
        output_types = [pv.get_value_as_python() for pv in pv_output_types]

        # Check that we got the correct values
        # The order is assured consistent by the sort in model_run.get_parameter_values()
        output_var_1 = self.model_run_service.get_output_variable_by_id(1)
        output_var_2 = self.model_run_service.get_output_variable_by_id(2)
        output_var_3 = self.model_run_service.get_output_variable_by_id(3)
        assert_that(var_vals, is_([output_var_1.name, output_var_1.name, output_var_2.name,
                                   output_var_2.name, output_var_3.name]))
        assert_that(nvars_vals, is_([1, 1, 1, 1, 1]))
        assert_that(profile_name_vals, is_([output_var_1.name + '_yearly', output_var_1.name + '_monthly',
                                            output_var_2.name + '_daily', output_var_2.name + '_hourly',
                                            output_var_3.name + '_monthly']))
        assert_that(output_main_run_vals, is_([True, True, True, True, True]))
        assert_that(output_period_vals, is_([-2, -1, JULES_DAILY_PERIOD, JULES_HOURLY_PERIOD, -1]))
        assert_that(output_types, is_(['M', 'M', 'M', 'M', 'M']))

    def test_GIVEN_selected_outputs_WHEN_go_back_THEN_previous_paged_rendered(self):
        params = self.valid_params
        params['submit'] = u'Back'
        response = self.app.post(
            url(controller='model_run', action='output'),
            params=params)
        assert_that(response.status_code, is_(302), "Response is redirect")
        assert_that(urlparse(response.response.location).path,
                    is_(url(controller='model_run', action='land_cover')), "url")

    def test_GIVEN_nsmax_set_zero_WHEN_page_get_THEN_nsmax_parameters_not_available_on_page(self):
        self.model_run_service.save_parameter(JULES_PARAM_NSMAX, 0, self.user)
        response = self.app.get(
            url(controller='model_run', action='output'))
        for output_name in DEPENDS_ON_NSMAX:
            assert_that(response.normal_body, is_not(contains_string(output_name)))

    def test_GIVEN_nsmax_set_three_WHEN_page_get_THEN_nsmax_parameters_shown_on_page(self):
        self.model_run_service.save_parameter(JULES_PARAM_NSMAX, 3, self.user)
        response = self.app.get(
            url(controller='model_run', action='output'))
        output_variables = self.model_run_service.get_output_variables(include_depends_on_nsmax=True)
        for output_variable in output_variables:
            if output_variable.depends_on_nsmax:
                assert_that(response.normal_body, contains_string(str(output_variable.name)))

    def test_GIVEN_page_already_run_once_WHEN_page_post_THEN_new_parameters_overwrite_old_parameters(self):
        self.app.post(
            url(controller='model_run', action='output'),
            params=self.valid_params)
        new_params = {
            'submit': u'Next',
            'ov_select_1': 1,
            'ov_hourly_1': 1,
            'ov_select_10': 1,
            'ov_yearly_10': 1,
            'ov_monthly_10': 1
        }
        self.app.post(
            url(controller='model_run', action='output'),
            params=new_params)

        model_run = self.model_run_service.get_model_being_created_with_non_default_parameter_values(self.user)

        # Check we have the right number of profiles
        n_expected = 3
        p_output_nprofiles = model_run.get_parameter_values(JULES_PARAM_OUTPUT_NPROFILES)[0].get_value_as_python()
        assert_that(p_output_nprofiles, is_(n_expected))

        pv_var = model_run.get_parameter_values(JULES_PARAM_OUTPUT_VAR)
        pv_nvars = model_run.get_parameter_values(JULES_PARAM_OUTPUT_NVARS)
        pv_profile_name = model_run.get_parameter_values(JULES_PARAM_OUTPUT_PROFILE_NAME)
        pv_output_main_run = model_run.get_parameter_values(JULES_PARAM_OUTPUT_MAIN_RUN)
        pv_output_period = model_run.get_parameter_values(JULES_PARAM_OUTPUT_PERIOD)
        pv_output_types = model_run.get_parameter_values(JULES_PARAM_OUTPUT_TYPE)

        # Check they are all 3 (not 4 anymore)
        assert_that(len(pv_var), is_(n_expected))
        assert_that(len(pv_nvars), is_(n_expected))
        assert_that(len(pv_profile_name), is_(n_expected))
        assert_that(len(pv_output_main_run), is_(n_expected))
        assert_that(len(pv_output_period), is_(n_expected))
        assert_that(len(pv_output_types), is_(n_expected))

        # Create list of values so we can check they are correct (easier than checking ParameterValue objects)
        var_vals = [pv.get_value_as_python() for pv in pv_var]
        nvars_vals = [pv.get_value_as_python() for pv in pv_nvars]
        profile_name_vals = [pv.get_value_as_python() for pv in pv_profile_name]
        output_main_run_vals = [pv.get_value_as_python() for pv in pv_output_main_run]
        output_period_vals = [pv.get_value_as_python() for pv in pv_output_period]
        output_types = [pv.get_value_as_python() for pv in pv_output_types]

        # Check that we got the correct values
        # The order is assured consistent by the sort in model_run.get_parameter_values()
        output_var_1 = self.model_run_service.get_output_variable_by_id(1)
        output_var_10 = self.model_run_service.get_output_variable_by_id(10)
        assert_that(var_vals, is_([output_var_1.name, output_var_10.name, output_var_10.name]))
        assert_that(nvars_vals, is_([1, 1, 1]))
        assert_that(profile_name_vals, is_([output_var_1.name + '_hourly', output_var_10.name + '_yearly',
                                            output_var_10.name + '_monthly']))
        assert_that(output_main_run_vals, is_([True, True, True]))
        assert_that(output_period_vals, is_([JULES_HOURLY_PERIOD, -2, -1]))
        assert_that(output_types, is_(['M', 'M', 'M']))