0

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

But in your example break will be executed always, not only when this method is used in a testcase.
Sorry I misread your original question. I've updated my answer with a solution that won't force you to change your source.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.