title: How to test field value for an object that should be in a list mixed with other objects of different classes?
body: <p>I am using pytest and <strong><em>trying to check if an object has the right content in one of its fields</em></strong>. The issue I face is that <strong><em>the object comes in a list where it could be in any position and mixed with objects from different classes</em></strong> where that field won't even exist.</p>
  
  <p>Below you have an example that tests what I need. The example works as it should but I think this is not a great solution because it is testing 2 conditions in a test (instance in list and correct content if it finds the instance) and also because having to break the test function does not seem very clean.</p>
  
  <p>Does anyone have advice on a more elegant and correct way to test this?</p>
  
  <pre><code>import pytest
  
  class Foo:
      def __init__(self,name):
          self.name = name
  
  class Bar:
      pass
  
  def test_instance_in_list():
  
      l = [Bar(), Foo('foo'), Bar()]                      # Will pass the test
  #    l = [Bar(), Bar(), Bar()]                     # Will NOT pass the test - "No instance"
  #    l = [Bar(), Foo('other name'), Bar()]     # Will NOT pass the test - "Assertion fail"
  
      for item in l:
          if isinstance(item,Foo):
              assert item.name == 'foo'
              return
      pytest.fail("There wasn't a Foo instance in the list")
  </code></pre>
  
  <p>The expected outputs of running the test for the three conditions are:</p>
  
  <p><strong><em>Results of running with l = [Bar(), Foo('foo'), Bar()]</em></strong></p>
  
  <pre><code>test_is_instance.py .                                                           [100%]
  
  ================================== 1 passed in 0.01s ==================================
  </code></pre>
  
  <p><strong><em>Results of running with l = [Bar(), Bar(), Bar()]</em></strong></p>
  
  <pre><code>&gt;       pytest.fail("There wasn't a Foo instance in the list")
  E       Failed: There wasn't a Foo instance in the list
  
  test_is_instance.py:21: Failed
  ================================== 1 failed in 0.03s ==================================
  </code></pre>
  
  <p><strong><em>Results of running with  l = [Bar(), Foo('other name'), Bar()]</em></strong></p>
  
  <pre><code>&gt;               assert item.name == 'foo'
  E               AssertionError: assert 'something else' == 'foo'
  E                 - something else
  E                 + foo
  
  test_is_instance.py:18: AssertionError
  ================================== 1 failed in 0.03s ==================================
  </code></pre>
  
  <p>Thanks for your advice and help to find a better way of getting the same results :-) !!</p>