r/Python • • Nov 14 '17

Senior Python Programmers, what tricks do you want to impart to us young guns?

Like basic looping, performance improvement, etc.

1.3k Upvotes

629 comments sorted by

View all comments

Show parent comments

2

u/admiralspark Nov 16 '17

Any thoughts on how to run tests against code that requires connecting to a device and pulling information? My code connects to say, a network switch and pulls or works with data from that live system, so unless I can carry the switch with me (not happening) I can't reproduce 'tests' anywhere.

I considered building a test to feed the scripts static data but it would require a bunch of refactoring and changes that would complicate code intended to be simple enough for new network engineers to grab. But right now, I just run it against a switch and make the determination myself if it's right or not....plus, simulating an SSH session seems like a mountain of work.

2

u/confusedpublic Nov 16 '17 edited Nov 16 '17

You need to learn how to mock that data:

Basically, you use mock to replace the function that returns the values from the service you connect to with a 'function' that 'returns' the value(s) you want to test. pseudo code:

@replace.function.thatConnects.to.device
def first_test():
    function.thatConnects.to.device.return_value = 'static_return_value'

    test_data = [1, 2, 3]
    test_result = operation_reliant_on_device_return_value(test_data)

    assert test_result = 3

You want to test as small a piece of code as possible, and for that code to be as static as possible. Unless you're writing a test for the connection explicitly, you're only interested in the value that connection provides.

If you're interested in multiple values, you can then look up side effects, and basically iterate over a range of values in a test (useful for if you want to test how your iterators before, or if you want something to fail/recover after n attempts)

but it would require a bunch of refactoring and changes that would complicate code intended to be simple enough for new network engineers to grab.

Attempting to identify and test a unit of code will often lead to refactoring, and that refactoring is often a good thing! You're right though - attempting to test something shouldn't make it harder. If it is, you're probably going about it the wrong way, so take a step back, identify what you're attempting to do, then try to google for analogous situations, or for the most basic description of what you're doing (how do I test functions dependant upon remote connections? for example)

2

u/admiralspark Nov 16 '17

This is awesome, thanks for the detailed reply!

2

u/confusedpublic Nov 16 '17

No problem. It’s a really powerful part of testing. Once you get your head around it you’ll be writing much better tests and code I hope!