'Ensure that Q-objects handle ANDing ORed components.'

def test_and_or_combination(self):

    class TestDoc(Document, ):
        x = IntField()
        y = BooleanField()
    TestDoc.drop_collection()
    query = (Q(x__gt=0) | Q(x__exists=False))
    query &= Q(x__lt=100)
    self.assertEqual(query.to_query(TestDoc), {'$and': [{'$or': [{'x': {'$gt': 0}}, {'x': {'$exists': False}}]}, {'x': {'$lt': 100}}]})
    q1 = (Q(x__gt=0) | Q(x__exists=False))
    q2 = (Q(x__lt=100) | Q(y=True))
    query = (q1 & q2).to_query(TestDoc)
    TestDoc(x=101).save()
    TestDoc(x=10).save()
    TestDoc(y=True).save()
    self.assertEqual(query, {'$and': [{'$or': [{'x': {'$gt': 0}}, {'x': {'$exists': False}}]}, {'$or': [{'x': {'$lt': 100}}, {'y': True}]}]})
    self.assertEqual(2, TestDoc.objects((q1 & q2)).count())
