def test_opened_database_commits_on_exit(self): config_file = os.path.join(self.make_dir(), "config") config_key = factory.make_name("key") config_value = factory.make_name("value") with ConfigurationDatabase.open_for_update(config_file) as config: config[config_key] = config_value with ConfigurationDatabase.open(config_file) as config: self.assertEqual(config_value, config[config_key])
def test_open_and_close(self): # ConfigurationDatabase.open() returns a context manager that closes # the database on exit. config_file = os.path.join(self.make_dir(), "config") config = ConfigurationDatabase.open_for_update(config_file) self.assertIsInstance(config, contextlib._GeneratorContextManager) with config as config: self.assertIsInstance(config, ConfigurationDatabase) with config.cursor() as cursor: self.assertEqual((1, ), cursor.execute("SELECT 1").fetchone()) self.assertRaises(sqlite3.ProgrammingError, config.cursor)
def test_opened_database_rolls_back_on_unclean_exit(self): config_file = os.path.join(self.make_dir(), "config") config_key = factory.make_name("key") config_value = factory.make_name("value") exception_type = factory.make_exception_type() # Set a configuration option, then crash. with ExpectedException(exception_type): with ConfigurationDatabase.open_for_update(config_file) as config: config[config_key] = config_value raise exception_type() # No value has been saved for `config_key`. with ConfigurationDatabase.open(config_file) as config: self.assertRaises(KeyError, lambda: config[config_key])
def test_open_for_update_yields_mutable_backend(self): config_file = os.path.join(self.make_dir(), "config") config_key = factory.make_name("key") with ConfigurationDatabase.open_for_update(config_file) as config: config[config_key] = factory.make_name("value") del config[config_key]