def create_from_yaml(cls, yaml_file, user, title, category, exploration_id=None, image_id=None): """Creates an exploration from a YAML file.""" init_state_name = yaml_file[: yaml_file.index(":\n")] if not init_state_name or "\n" in init_state_name: raise Exception( "Invalid YAML file: the name of the initial state " "should be left-aligned on the first line and " "followed by a colon" ) exploration = cls.create( user, title, category, exploration_id=exploration_id, init_state_name=init_state_name, image_id=image_id ) init_state = State.get_by_name(init_state_name, exploration) try: exploration_dict = utils.dict_from_yaml(yaml_file) state_list = [] for state_name, state_description in exploration_dict.iteritems(): state = init_state if state_name == init_state_name else exploration.add_state(state_name) state_list.append({"state": state, "desc": state_description}) for index, state in enumerate(state_list): State.modify_using_dict(exploration, state["state"], state["desc"]) except Exception: exploration.delete() raise return exploration
def test_create_and_get_state(self): """Test creation and retrieval of states.""" id_1 = "123" name_1 = "State 1" state_1 = State.create(self.exploration, name_1, state_id=id_1) fetched_state_1 = State.get(id_1, parent=self.exploration.key) self.assertEqual(fetched_state_1, state_1) fetched_state_by_name_1 = State.get_by_name(name_1, self.exploration) self.assertEqual(fetched_state_by_name_1, state_1) # Test the failure cases. id_2 = "fake_id" name_2 = "fake_name" with self.assertRaises(Exception): State.get(id_2, parent=self.exploration.key) fetched_state_by_name_2 = State.get_by_name(name_2, self.exploration, strict=False) self.assertIsNone(fetched_state_by_name_2) with self.assertRaises(Exception): State.get_by_name(name_2, self.exploration, strict=True) # The default behavior is to fail noisily. with self.assertRaises(Exception): State.get_by_name(name_2, self.exploration)