def test_cached_parent(): class HasParent(XBlock): """ Dummy empty class """ pass runtime = TestRuntime(services={'field-data': DictFieldData({})}) runtime.get_block = Mock() block = HasParent(runtime, scope_ids=Mock(spec=ScopeIds)) # block has no parent yet, and we don't need to call the runtime to find # that out. assert_equals(block.get_parent(), None) assert not runtime.get_block.called # Set a parent id for the block. Get the parent. Now we have one, and we # used runtime.get_block to get it. block.parent = "some_parent_id" parent = block.get_parent() assert_not_equals(parent, None) assert runtime.get_block.called_with("some_parent_id") # Get the parent again. It will be the same parent, and we didn't call the # runtime. runtime.get_block.reset_mock() parent2 = block.get_parent() assert parent2 is parent assert not runtime.get_block.called
class TestRuntimeGetBlock(TestCase): """ Test the get_block default method on Runtime. """ def setUp(self): patcher = patch.object(TestRuntime, 'construct_xblock') self.construct_block = patcher.start() self.addCleanup(patcher.stop) self.id_reader = Mock(IdReader) self.user_id = Mock() self.field_data = Mock(FieldData) self.runtime = TestRuntime(self.id_reader, services={'field-data': self.field_data}) self.runtime.user_id = self.user_id self.usage_id = 'usage_id' # Can only get a definition id from the id_reader self.def_id = self.id_reader.get_definition_id.return_value # Can only get a block type from the id_reader self.block_type = self.id_reader.get_block_type.return_value def test_basic(self): self.runtime.get_block(self.usage_id) self.id_reader.get_definition_id.assert_called_with(self.usage_id) self.id_reader.get_block_type.assert_called_with(self.def_id) self.construct_block.assert_called_with( self.block_type, ScopeIds(self.user_id, self.block_type, self.def_id, self.usage_id), for_parent=None, ) def test_missing_usage(self): self.id_reader.get_definition_id.side_effect = NoSuchUsage with self.assertRaises(NoSuchUsage): self.runtime.get_block(self.usage_id) def test_missing_definition(self): self.id_reader.get_block_type.side_effect = NoSuchDefinition # If we don't have a definition, then the usage doesn't exist with self.assertRaises(NoSuchUsage): self.runtime.get_block(self.usage_id)