Database Dependency

create_maya_scene can now start to execute. During the execution of create_maya_scene, there is an issue with the database connection. The code wants to load previous files for the shot from the database. Because nothing was stored in the database before, querying the database fails. There are two options to solve this issue:

  1. Insert the File and Shot instances into the database
  2. Mock the database query.

Inserting in the database has several drawbacks: a database connection is required to run the tests, and the database is modified each time the tests are run. So mocking is the cleaner option. To see which part of the code needs to be mocked, let’s take a look at the corresponding code section:

[...]

    if current:
        if not current.parent == parent:
            raise TypeError('If "current" file is set - the parent must be the same as the given "parent"!')
        previous_file = [f for f in session.query(File).filter(File.filetype == current.filetype)
                         .filter(File.shot == current.shot)
                         .filter(File.bundle == current.bundle)
                         .filter(File.name == current.name)
                         .filter(File.is_deleted == 0)
                         .order_by(File.version.desc())
                         .all() if f.extension == '.ma']
[...]

The critical part is the generator expression in the square brackets. There is nothing more that is required to query the database. If this code section is extracted into a method, this method can be easily mocked in a test.

Mixing database queries directly in your code is bad practice for two reasons:

  1. It’s hard to exchange the database/database framework afterward if the code is distributed to the whole codebase.
  2. It’s hard to test.

A better approach would be to encapsulate the code related to database queries into separate classes with an abstract interface. See section Dealing with dependencies/databases for futher information. Maybe it’s possible to refactor the code later.

Last modified August 24, 2020