views:

36

answers:

2

Hi, I have a time-consuming method with non-predefined number of iterations inside it that I need to test:

def testmethod():
    objects = get_objects()
    for objects in objects:
        # Time-consuming iterations
        do_something(object)

One iteration is sufficient to test for me. What is the best practice to test this method with one iteration only?

+2  A: 

Perhaps turn your method into

def my_method(self, objs=None):
    if objs is None:
        objs = get_objects()
    for obj in objs:
        do_something(obj)

Then in your test you can call it with a custom objs parameter.

Alex Gaynor
Thanks. I will try this
dragoon
+2  A: 

Update:

I misread the original question, so here's how I would solve the problem without altering the source code:

Lambda out your call to get objects to return a single object. For example:

from your_module import get_objects

def test_testmethdod(self):
    original_get_objects = get_objects
    one_object = YourObject()
    get_objects = lambda : [one_object,]

    # ...
    # your tests here
    # ...

    # Reset the original function, so it doesn't mess up other tests
    get_objects = original_get_objects
sdolan
But in your example break will be executed always, not only when this method is used in a testcase.
dragoon
Sorry I misread your original question. I've updated my answer with a solution that won't force you to change your source.
sdolan
Ok, I understand your solution, I also use it in other test, but in this case I'll use Alex's technique, vote up anyway
dragoon