https://dagster.io/ logo
#ask-community
Title
# ask-community
m

Matthew Karas

05/20/2022, 3:02 PM
Hello Dagster! I am trying to write tests around Dagster - in particular the ResourceDefinition.mock_resource. I'm having trouble setting up the mock to return values when its running in a unit test. The example presented in the change log just checks the presence of a mocked resource, but doesn't really show how to get the mock to return values when inside a test.
🤖 1
z

Zach

05/20/2022, 3:37 PM
Is your question in particular how to use MagicMock and set return values?
j

jamie

05/20/2022, 3:44 PM
hi @Matthew Karas in the case where you need very specific custom mock behavior you may be better off writing your own resource. this would be exactly like writing a custom resource but you would fill in all the methods of the resource with their mock implementations. For example, if you wanted to mock a DB resource with an in memory dictionary, you'll probably want to do something like
Copy code
@resource 
def mock_db_resource():
   return MockDBResource()

class MockDBResource:
   def __init__(self):
      self.db = {}
   def add_item(self, item):
       self.db[item.name] = item
   ....
where your MockDBResource implements the same methods as your normal db resource
m

Matthew Karas

05/20/2022, 3:55 PM
thanks! I'll look into it. But @Zach - yeah the issue is that the ResourceDefinition.mock_resource won't let you work on the mock that the resources provides. There's no way to get at it as far as I can see when I was debugging. There's no property - and when I try to call it - a new mock is returned all the time so I can't set anything.
z

Zach

05/20/2022, 3:59 PM
Kind of what @jamie was getting at - you might just want to provide your own real (mocked) resource that just returns a MagicMock (if you want to use the MagicMock interface). So with @jamie's example you could do something like:
Copy code
@resource 
def mock_db_resource():
   mock_db_resource = MagicMock()
   mock_db_resource.query.return_value = [{'a': 1, 'b': 2}]
   return mock_db_resource
then you just use the mock_db_resource in your tests when testing the op / job
m

Matthew Karas

05/20/2022, 4:09 PM
right - awesome - thanks - have a good one
13 Views