def test_export_to_python_default_args(self): """Export a python script w/ default args for a model.""" from natcap.invest import cli filename = 'foo.py' target_filepath = os.path.join(self.workspace_dir, filename) target_model = 'carbon' expected_data = 'natcap.invest.carbon.execute(args)' cli.export_to_python(target_filepath, target_model) self.assertTrue(os.path.exists(target_filepath)) target_model = cli._MODEL_UIS[target_model].pyname model_module = importlib.import_module(name=target_model) spec = model_module.ARGS_SPEC expected_args = {key: '' for key in spec['args'].keys()} module_name = str(uuid.uuid4()) + 'testscript' spec = importlib.util.spec_from_file_location(module_name, target_filepath) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) self.assertEqual(module.args, expected_args) data_in_file = False with open(target_filepath, 'r') as file: for line in file: if expected_data in line: data_in_file = True break self.assertTrue(data_in_file)
def save_to_python(): """Writes a python script with a call to an InVEST model execute function. Body (JSON string): filepath: string modelname: string (e.g. carbon) args_dict: JSON string of InVEST model args keys and values Returns: A string. """ payload = request.get_json() save_filepath = payload['filepath'] modelname = payload['modelname'] args_dict = json.loads(payload['args']) cli.export_to_python(save_filepath, modelname, args_dict) return 'python script saved'
def test_export_to_python_with_args(self): """Export a python script w/ args for a model.""" from natcap.invest import cli target_filepath = os.path.join(self.workspace_dir, 'foo.py') target_model = 'carbon' expected_args = { 'workspace_dir': 'myworkspace', 'lulc': 'myraster.tif', 'parameter': 0.5, } cli.export_to_python(target_filepath, target_model, expected_args) self.assertTrue(os.path.exists(target_filepath)) module_name = str(uuid.uuid4()) + 'testscript' spec = importlib.util.spec_from_file_location(module_name, target_filepath) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) self.assertEqual(module.args, expected_args)