Refactoring Tools
The code section needs to be extracted into a method. It’s strongly recommended to use an IDE or an editor that offers refactoring tools. This guideline focuses on PyCharm. PyCharm’s refactoring tools do a pretty good job. To learn more about PyCharm’s refactoring tools, click here.
The benefit of using the refactoring tools of the IDE is that they are pretty safe to use. They know the structure of the code. You could try to extract the function by defining the function by hand and copying and pasting the code into it. But it’s possible that the copied code still references a variable that was not copied. This will cause errors at runtime. However, if the refactoring tools of an IDE are used, the IDE will pass these variables as parameters to the new function. This way, the code can be changed without breaking it. Since the IDE will ensure that the code still works correctly, no test needs to be written in advance to detect errors.
So the code gets extracted, which results in:
[...]
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 = query_previous_files(current, session)
[...]
def query_previous_files(current, session):
return [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']
Now the function query_previous_files
can be mocked in the test code:
@mock.patch("[...].query_previous_files")
def test_create_maya_scene(mock_query_previous_files):
shot = Shot('myAwesomeShot')
user = User('Jan Honsbrok', 'janhon')
current = File(shot=shot)
mock_query_previous_files.return_value = [File(shot=shot, name='test', filetype='filetype', version=0)]
create_maya_scene(shot, user=user, current=current)