In general its much easier to test scripts when they have been heavily modularized. The .py file that the toolbox points to, or the .pyt file for Python toolboxes can both be very 'thin' in that they only need to handle the importing of arcpy and the parameter i/o, then the rest of the logic split across several modules which are imported. This makes testing those modules easier, as they can be separated into those which require arcpy and those that don't.
For example, rather than having a section of the script which processes each row in a feature class within a loop, break that logic out of the main script into an arcpy-bound function which takes a path to a table and list of fields, then generates rows from the table via an arcpy.da.cursor. This function can easily be mocked to return tuples, because it can be called independently of the main script. This also allows you to easily debug this code in an IDE, since it can be run completely independently of the ArcGIS UI at that point.
Thanks that's a great tutorial! I hadn't seen it before.
For arcpy functions, I use the mock library. Here is a basic example:
import scriptRefimport unittestfrom mock import mock
class ScriptUnitTests(unittest.TestCase):
@mock.patch('arcpy.da')
def test_when_starting_session_should_start_edtior(self, mock_da):
variables = " "
scriptRef.scriptMethod(variables)
mock_da.Editor.assert_called_with(variables)
I also recommend this article for helpful arcpy testing strategies:
Testing with ArcPy: Isolation and Mocking· Notes from the Lifeboat
Hi,Our python script library is starting to get large and complex to the point that we are introducing unit testing to keep problems manageable.Has anyone had any experience creating Unit Tests for their python. How did you mock ArcGIS objects?Thanks
Signed in members can post, follow updates, and more. New here? Register a free account.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.