internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: MongoEngine/mongoengine

Issue:
switch_db method docs may be not right.
Here is the docs:
"If you need to read from another database see
 :class:`~mongoengine.context_managers.switch_db`"

I think that it should be a reference to method "switch_collection",
so change to below:
"If you need to read from another collection see
 :class:`~mongoengine.context_managers.switch_collection`".



Discussion:

Resolving patch:
diff --git a/mongoengine/document.py b/mongoengine/document.py
--- a/mongoengine/document.py
+++ b/mongoengine/document.py
@@ -462,10 +462,11 @@ def switch_db(self, db_alias):
             user.switch_db('archive-db')
             user.save()
 
-        If you need to read from another database see
-        :class:`~mongoengine.context_managers.switch_db`
+        :param str db_alias: The database alias to use for saving the document
 
-        :param db_alias: The database alias to use for saving the document
+        .. seealso::
+            Use :class:`~mongoengine.context_managers.switch_collection`
+            if you need to read from another collection
         """
         with switch_db(self.__class__, db_alias) as cls:
             collection = cls._get_collection()
@@ -488,11 +489,12 @@ def switch_collection(self, collection_name):
             user.switch_collection('old-users')
             user.save()
 
-        If you need to read from another database see
-        :class:`~mongoengine.context_managers.switch_db`
-
-        :param collection_name: The database alias to use for saving the
+        :param str collection_name: The database alias to use for saving the
             document
+
+        .. seealso::
+            Use :class:`~mongoengine.context_managers.switch_db`
+            if you need to read from another database
         """
         with switch_collection(self.__class__, collection_name) as cls:
             collection = cls._get_collection()


Test patch:
Repository: MongoEngine/mongoengine

Issue:
No module named 'django.utils.importlib' (Django dev)
In mongoengine/django/mongo_auth/models.py
See https://github.com/django/django/tree/master/django/utils

No module named 'django.utils.importlib' (Django dev)
In mongoengine/django/mongo_auth/models.py
See https://github.com/django/django/tree/master/django/utils



Discussion:

Resolving patch:
diff --git a/mongoengine/django/mongo_auth/models.py b/mongoengine/django/mongo_auth/models.py
--- a/mongoengine/django/mongo_auth/models.py
+++ b/mongoengine/django/mongo_auth/models.py
@@ -3,7 +3,11 @@
 from django.contrib.auth.models import UserManager
 from django.core.exceptions import ImproperlyConfigured
 from django.db import models
-from django.utils.importlib import import_module
+try:
+    from django.utils.module_loading import import_module
+except ImportError:
+    """Handle older versions of Django"""
+    from django.utils.importlib import import_module
 from django.utils.translation import ugettext_lazy as _
 
 


Test patch:
diff --git a/tests/test_django.py b/tests/test_django.py
--- a/tests/test_django.py
+++ b/tests/test_django.py
@@ -19,9 +19,12 @@
     AUTHENTICATION_BACKENDS = ('mongoengine.django.auth.MongoEngineBackend',)
 )
 
-# For Django >= 1.7
-if hasattr(django, 'setup'):
-    django.setup()
+try:
+    # For Django >= 1.7
+    if hasattr(django, 'setup'):
+        django.setup()
+except RuntimeError:
+    pass
 
 try:
     from django.contrib.auth import authenticate, get_user_model
@@ -34,7 +37,6 @@
     DJ15 = True
 except Exception:
     DJ15 = False
-from django.contrib.sessions.tests import SessionTestsMixin
 from mongoengine.django.sessions import SessionStore, MongoSession
 from mongoengine.django.tests import MongoTestCase
 from datetime import tzinfo, timedelta
@@ -226,13 +228,13 @@ class Note(Document):
         self.assertEqual(t.render(c), "10")
 
 
-class MongoDBSessionTest(SessionTestsMixin, unittest.TestCase):
+class _BaseMongoDBSessionTest(unittest.TestCase):
     backend = SessionStore
 
     def setUp(self):
         connect(db='mongoenginetest')
         MongoSession.drop_collection()
-        super(MongoDBSessionTest, self).setUp()
+        super(_BaseMongoDBSessionTest, self).setUp()
 
     def assertIn(self, first, second, msg=None):
         self.assertTrue(first in second, msg)
@@ -259,6 +261,21 @@ def test_session_expiration_tz(self):
         self.assertTrue('test_expire' in session, 'Session has expired before it is expected')
 
 
+try:
+    # SessionTestsMixin isn't available for import on django > 1.8a1
+    from django.contrib.sessions.tests import SessionTestsMixin
+
+    class _MongoDBSessionTest(SessionTestsMixin):
+        pass
+
+    class MongoDBSessionTest(_BaseMongoDBSessionTest):
+        pass
+
+except ImportError:
+    class MongoDBSessionTest(_BaseMongoDBSessionTest):
+        pass
+
+
 class MongoAuthTest(unittest.TestCase):
     user_data = {
         'username': 'user',
Repository: MongoEngine/mongoengine

Issue:
Request Support for $min, $max Field update operators
MongoEngine currently has support for several (but not all) [field Update Operators](http://docs.mongodb.org/manual/reference/operator/update/).  I would REALLY like to have support for [$min](http://docs.mongodb.org/manual/reference/operator/update/min/) and [$max](http://docs.mongodb.org/manual/reference/operator/update/max/) (field) Update Oerators.

Thanks in advance !

Scott

Request Support for $min, $max Field update operators
MongoEngine currently has support for several (but not all) [field Update Operators](http://docs.mongodb.org/manual/reference/operator/update/).  I would REALLY like to have support for [$min](http://docs.mongodb.org/manual/reference/operator/update/min/) and [$max](http://docs.mongodb.org/manual/reference/operator/update/max/) (field) Update Oerators.

Thanks in advance !

Scott



Discussion:
For what its worth, indirect access to `$min` and `$max` functionality can be gained using the `__raw__` parameter to the `query()` method:

`attribs.objects(name='Mag')[0].update(__raw__={'$min': {'min_value': 4.9}})`

For what its worth, indirect access to `$min` and `$max` functionality can be gained using the `__raw__` parameter to the `query()` method:

`attribs.objects(name='Mag')[0].update(__raw__={'$min': {'min_value': 4.9}})`


Resolving patch:
diff --git a/mongoengine/queryset/transform.py b/mongoengine/queryset/transform.py
--- a/mongoengine/queryset/transform.py
+++ b/mongoengine/queryset/transform.py
@@ -26,7 +26,7 @@
 
 UPDATE_OPERATORS = ('set', 'unset', 'inc', 'dec', 'pop', 'push',
                     'push_all', 'pull', 'pull_all', 'add_to_set',
-                    'set_on_insert')
+                    'set_on_insert', 'min', 'max')
 
 
 def query(_doc_cls=None, _field_operation=False, **query):


Test patch:
diff --git a/tests/queryset/queryset.py b/tests/queryset/queryset.py
--- a/tests/queryset/queryset.py
+++ b/tests/queryset/queryset.py
@@ -510,6 +510,17 @@ class BlogPost(Document):
         self.assertEqual(post.comments[0].by, 'joe')
         self.assertEqual(post.comments[0].votes.score, 4)
 
+    def test_update_min_max(self):
+        class Scores(Document):
+            high_score = IntField()
+            low_score = IntField()
+        scores = Scores(high_score=800, low_score=200)
+        scores.save()
+        Scores.objects(id=scores.id).update(min__low_score=150)
+        self.assertEqual(Scores.objects(id=scores.id).get().low_score, 150)
+        Scores.objects(id=scores.id).update(min__low_score=250)
+        self.assertEqual(Scores.objects(id=scores.id).get().low_score, 150)
+
     def test_updates_can_have_match_operators(self):
 
         class Comment(EmbeddedDocument):
Repository: MongoEngine/mongoengine

Issue:
ListField of embedded docs doesn't set the _instance attribute when iterating over it
It sets it for **getitem** but not for **iter**. Example:

[i._instance for i in parent.children] # [None, None, None]
parent.children[0]._instance == parent # True



Discussion:

Resolving patch:
diff --git a/mongoengine/base/datastructures.py b/mongoengine/base/datastructures.py
--- a/mongoengine/base/datastructures.py
+++ b/mongoengine/base/datastructures.py
@@ -125,6 +125,10 @@ def __getitem__(self, key, *args, **kwargs):
             value._instance = self._instance
         return value
 
+    def __iter__(self):
+        for i in xrange(self.__len__()):
+            yield self[i]
+
     def __setitem__(self, key, value, *args, **kwargs):
         if isinstance(key, slice):
             self._mark_as_changed()


Test patch:
diff --git a/tests/document/instance.py b/tests/document/instance.py
--- a/tests/document/instance.py
+++ b/tests/document/instance.py
@@ -2799,5 +2799,21 @@ class Person(Document):
         self.assertNotEqual(p, p1)
         self.assertEqual(p, p)
 
+    def test_list_iter(self):
+        # 914
+        class B(EmbeddedDocument):
+            v = StringField()
+
+        class A(Document):
+            l = ListField(EmbeddedDocumentField(B))
+
+        A.objects.delete()
+        A(l=[B(v='1'), B(v='2'), B(v='3')]).save()
+        a = A.objects.get()
+        self.assertEqual(a.l._instance, a)
+        for idx, b in enumerate(a.l):
+            self.assertEqual(b._instance, a)
+        self.assertEqual(idx, 2)
+
 if __name__ == '__main__':
     unittest.main()
Repository: MongoEngine/mongoengine

Issue:
chaining only after limit
Maybe this is obvious but I was using `only` after `limit` and didn't understand why the `only` call had no effect. Would it be helpful to have this documented in the API?

So

```
Document.limit(1000).only('field')
```

was the same as

```
Document.limit(1000)
```



Discussion:

Resolving patch:
diff --git a/mongoengine/queryset/base.py b/mongoengine/queryset/base.py
--- a/mongoengine/queryset/base.py
+++ b/mongoengine/queryset/base.py
@@ -684,11 +684,7 @@ def limit(self, n):
         :param n: the maximum number of objects to return
         """
         queryset = self.clone()
-        if n == 0:
-            queryset._cursor.limit(1)
-        else:
-            queryset._cursor.limit(n)
-        queryset._limit = n
+        queryset._limit = n if n != 0 else 1
         # Return self to allow chaining
         return queryset
 
@@ -699,7 +695,6 @@ def skip(self, n):
         :param n: the number of objects to skip before returning results
         """
         queryset = self.clone()
-        queryset._cursor.skip(n)
         queryset._skip = n
         return queryset
 
@@ -717,7 +712,6 @@ def hint(self, index=None):
         .. versionadded:: 0.5
         """
         queryset = self.clone()
-        queryset._cursor.hint(index)
         queryset._hint = index
         return queryset
 


Test patch:
diff --git a/tests/document/indexes.py b/tests/document/indexes.py
--- a/tests/document/indexes.py
+++ b/tests/document/indexes.py
@@ -577,11 +577,11 @@ class BlogPost(Document):
             self.assertEqual(BlogPost.objects.hint('tags').count(), 10)
         else:
             def invalid_index():
-                BlogPost.objects.hint('tags')
+                BlogPost.objects.hint('tags').next()
             self.assertRaises(TypeError, invalid_index)
 
         def invalid_index_2():
-            return BlogPost.objects.hint(('tags', 1))
+            return BlogPost.objects.hint(('tags', 1)).next()
         self.assertRaises(Exception, invalid_index_2)
 
     def test_unique(self):
diff --git a/tests/queryset/queryset.py b/tests/queryset/queryset.py
--- a/tests/queryset/queryset.py
+++ b/tests/queryset/queryset.py
@@ -188,6 +188,10 @@ def test_find(self):
             "[<Person: Person object>, <Person: Person object>]",  "%s" % self.Person.objects[1:3])
         self.assertEqual(
             "[<Person: Person object>, <Person: Person object>]",  "%s" % self.Person.objects[51:53])
+        # Test only after limit
+        self.assertEqual(self.Person.objects().limit(2).only('name')[0].age, None)
+        # Test only after skip
+        self.assertEqual(self.Person.objects().skip(2).only('name')[0].age, None)
 
     def test_find_one(self):
         """Ensure that a query using find_one returns a valid result.
Repository: MongoEngine/mongoengine

Issue:
StrictDict & SemiStrictDict are shadowed at init time
Reading the code of BaseDocument class (see https://github.com/MongoEngine/mongoengine/blob/master/mongoengine/base/document.py#L88)

``` python

        if self.STRICT and not self._dynamic:
            self._data = StrictDict.create(allowed_keys=self._fields_ordered)()
        else:
            self._data = SemiStrictDict.create(
                allowed_keys=self._fields_ordered)()

        self._data = {}
```

So it seems the `_data` attribute is first assigned to a `StrictDict/SemiScrictDict` then re-assigned to a regular dict. Given there is no side-effects, I believe it's just a mistake from 5cc71ec2adad4e4601da50264c2d59ed5e32eb16 (fixing issue #635)

I guess we should fix this to only assigned `_data` once. Now I wonder the use of `StrictDict/SemiStrictDict` given this bug is remained silent for such a long time...



Discussion:
The purpose of `StrictDict/SemiStrictDict` is to reduce mongoengine memory consumption


Resolving patch:
diff --git a/mongoengine/base/document.py b/mongoengine/base/document.py
--- a/mongoengine/base/document.py
+++ b/mongoengine/base/document.py
@@ -85,7 +85,6 @@ def __init__(self, *args, **values):
             self._data = SemiStrictDict.create(
                 allowed_keys=self._fields_ordered)()
 
-        self._data = {}
         self._dynamic_fields = SON()
 
         # Assign default values to instance


Test patch:
Repository: MongoEngine/mongoengine

Issue:
Can not update documents with type of pk=int and value 0
Documents with pk type defined as `fields.IntField(primary_key=True)` fail to be updated giving following error:

```
Traceback (most recent call last):
  File "mongoengine_bug.py", line 12, in <module>
    doc.update(set__field='changed field')
  File "/usr/local/lib/python2.7/site-packages/mongoengine/document.py", line 474, in update
    'attempt to update a document not yet saved')
mongoengine.errors.OperationError: attempt to update a document not yet saved
```

Here is a self contained code which can reproduce this bug:

```
import mongoengine

mongoengine.connect('test_db')

class TestDocument(mongoengine.Document):
    id = mongoengine.fields.IntField(primary_key=True)
    field = mongoengine.fields.StringField()

doc = TestDocument(id=0, field='')
doc.save()

doc.update(set__field='changed field')
```

It seems that `mongoengine/document.py` line 466 is at fault:

```
 if not self.pk:
```

So if Document's id is 0 it is evaluated to false and throws exception
I think it should be changed to:

```
if self.pk is None:
```



Discussion:

Resolving patch:
diff --git a/mongoengine/document.py b/mongoengine/document.py
--- a/mongoengine/document.py
+++ b/mongoengine/document.py
@@ -472,7 +472,7 @@ def update(self, **kwargs):
         Raises :class:`OperationError` if called on an object that has not yet
         been saved.
         """
-        if not self.pk:
+        if self.pk is None:
             if kwargs.get('upsert', False):
                 query = self.to_mongo()
                 if "_cls" in query:
@@ -604,7 +604,7 @@ def reload(self, *fields, **kwargs):
         elif "max_depth" in kwargs:
             max_depth = kwargs["max_depth"]
 
-        if not self.pk:
+        if self.pk is None:
             raise self.DoesNotExist("Document does not exist")
         obj = self._qs.read_preference(ReadPreference.PRIMARY).filter(
             **self._object_key).only(*fields).limit(
@@ -655,7 +655,7 @@ def _reload(self, key, value):
     def to_dbref(self):
         """Returns an instance of :class:`~bson.dbref.DBRef` useful in
         `__raw__` queries."""
-        if not self.pk:
+        if self.pk is None:
             msg = "Only saved documents can have a valid dbref"
             raise OperationError(msg)
         return DBRef(self.__class__._get_collection_name(), self.pk)


Test patch:
diff --git a/tests/document/instance.py b/tests/document/instance.py
--- a/tests/document/instance.py
+++ b/tests/document/instance.py
@@ -3202,5 +3202,20 @@ class A(Document):
             self.assertEqual(b._instance, a)
         self.assertEqual(idx, 2)
 
+    def test_falsey_pk(self):
+        """Ensure that we can create and update a document with Falsey PK.
+        """
+        class Person(Document):
+            age = IntField(primary_key=True)
+            height = FloatField()
+
+        person = Person()
+        person.age = 0
+        person.height = 1.89
+        person.save()
+
+        person.update(set__height=2.0)
+
+
 if __name__ == '__main__':
     unittest.main()
Repository: MongoEngine/mongoengine

Issue:
Custom cursor filtering + the batch_size option for cursors isn't implemented
The batch_size option is very useful, but it isn't implemented in MongoEngine (but in pymongo).
http://api.mongodb.org/python/current/api/pymongo/cursor.html#pymongo.cursor.Cursor.batch_size

Is there any way to select MongoEngine models using a custom "batch_size" option for a cursor?



Discussion:

Resolving patch:
diff --git a/mongoengine/queryset/base.py b/mongoengine/queryset/base.py
--- a/mongoengine/queryset/base.py
+++ b/mongoengine/queryset/base.py
@@ -82,6 +82,7 @@ def __init__(self, document, collection):
         self._limit = None
         self._skip = None
         self._hint = -1  # Using -1 as None is a valid value for hint
+        self._batch_size = None
         self.only_fields = []
         self._max_time_ms = None
 
@@ -781,6 +782,19 @@ def hint(self, index=None):
         queryset._hint = index
         return queryset
 
+    def batch_size(self, size):
+        """Limit the number of documents returned in a single batch (each
+        batch requires a round trip to the server).
+
+        See http://api.mongodb.com/python/current/api/pymongo/cursor.html#pymongo.cursor.Cursor.batch_size
+        for details.
+
+        :param size: desired size of each batch.
+        """
+        queryset = self.clone()
+        queryset._batch_size = size
+        return queryset
+
     def distinct(self, field):
         """Return a list of distinct values for a given field.
 
@@ -1467,6 +1481,9 @@ def _cursor(self):
             if self._hint != -1:
                 self._cursor_obj.hint(self._hint)
 
+            if self._batch_size is not None:
+                self._cursor_obj.batch_size(self._batch_size)
+
         return self._cursor_obj
 
     def __deepcopy__(self, memo):


Test patch:
diff --git a/tests/queryset/queryset.py b/tests/queryset/queryset.py
--- a/tests/queryset/queryset.py
+++ b/tests/queryset/queryset.py
@@ -337,6 +337,34 @@ class B(Document):
         query = query.filter(boolfield=True)
         self.assertEqual(query.count(), 1)
 
+    def test_batch_size(self):
+        """Ensure that batch_size works."""
+        class A(Document):
+            s = StringField()
+
+        A.drop_collection()
+
+        for i in range(100):
+            A.objects.create(s=str(i))
+
+        # test iterating over the result set
+        cnt = 0
+        for a in A.objects.batch_size(10):
+            cnt += 1
+        self.assertEqual(cnt, 100)
+
+        # test chaining
+        qs = A.objects.all()
+        qs = qs.limit(10).batch_size(20).skip(91)
+        cnt = 0
+        for a in qs:
+            cnt += 1
+        self.assertEqual(cnt, 9)
+
+        # test invalid batch size
+        qs = A.objects.batch_size(-1)
+        self.assertRaises(ValueError, lambda: list(qs))
+
     def test_update_write_concern(self):
         """Test that passing write_concern works"""
         self.Person.drop_collection()
Repository: MongoEngine/mongoengine

Issue:
Drop Python 2.6 support
For the most relevant discussion about the topic, see #1294.

Plan:
1. In the upcoming minor release, I'm going to include `warnings.warn(msg, DeprecationWarning)`. with the message saying "Python v2.6 support is deprecated and is going to be dropped entirely in the upcoming v0.11.0 release. Update your Python version if you want to have access to the latest features and bug fixes in MongoEngine."
2. In v0.11.0 (most likely shipped with #1428), I'll update the way we do dict comprehensions and other relics of the past, thus making it truly incompatible with v2.6.

Cc @lafrech @gukoff 


Discussion:

Resolving patch:
diff --git a/mongoengine/python_support.py b/mongoengine/python_support.py
--- a/mongoengine/python_support.py
+++ b/mongoengine/python_support.py
@@ -1,9 +1,22 @@
-"""Helper functions and types to aid with Python 2.5 - 3 support."""
+"""Helper functions and types to aid with Python 2.6 - 3 support."""
 
 import sys
+import warnings
+
 import pymongo
 
 
+# Show a deprecation warning for people using Python v2.6
+# TODO remove in mongoengine v0.11.0
+if sys.version_info[0] == 2 and sys.version_info[1] == 6:
+    warnings.warn(
+        'Python v2.6 support is deprecated and is going to be dropped '
+        'entirely in the upcoming v0.11.0 release. Update your Python '
+        'version if you want to have access to the latest features and '
+        'bug fixes in MongoEngine.',
+        DeprecationWarning
+    )
+
 if pymongo.version_tuple[0] < 3:
     IS_PYMONGO_3 = False
 else:


Test patch:
Repository: MongoEngine/mongoengine

Issue:
Saving an abstract Document does not fail with a mongoengine.error
``` python
import mongoengine

mongoengine.connect()

class Project(mongoengine.Document):
    id = mongoengine.StringField()
    meta = {'abstract': True}

project = Project(id="TestProject")
project.save()
```

Running the above example fails with the following:

```
Traceback (most recent call last):
  File "test_project.py", line 10, in <module>
    project.save()
  File "C:\Python27\lib\site-packages\mongoengine\document.py", line 314, in save
    collection = self._get_collection()
  File "C:\Python27\lib\site-packages\mongoengine\document.py", line 207, in _get_collection
    cls._collection = db[collection_name]
  File "C:\Python27\lib\site-packages\pymongo\database.py", line 226, in __getitem__
    return Collection(self, name)
  File "C:\Python27\lib\site-packages\pymongo\collection.py", line 135, in __init__
    "of %s" % (string_type.__name__,))
TypeError: name must be an instance of basestring
```

I feel like it should fail with some mongoengine.error class rather than a TypeError.



Discussion:

Resolving patch:
diff --git a/mongoengine/document.py b/mongoengine/document.py
--- a/mongoengine/document.py
+++ b/mongoengine/document.py
@@ -313,6 +313,9 @@ def save(self, force_insert=False, validate=True, clean=True,
         .. versionchanged:: 0.10.7
             Add signal_kwargs argument
         """
+        if self._meta.get('abstract'):
+            raise InvalidDocumentError('Cannot save an abstract document.')
+
         signal_kwargs = signal_kwargs or {}
         signals.pre_save.send(self.__class__, document=self, **signal_kwargs)
 
@@ -828,7 +831,6 @@ def list_indexes(cls):
         """ Lists all of the indexes that should be created for given
         collection. It includes all the indexes from super- and sub-classes.
         """
-
         if cls._meta.get('abstract'):
             return []
 


Test patch:
diff --git a/tests/document/instance.py b/tests/document/instance.py
--- a/tests/document/instance.py
+++ b/tests/document/instance.py
@@ -435,6 +435,15 @@ def test_to_dbref(self):
 
         person.to_dbref()
 
+    def test_save_abstract_document(self):
+        """Saving an abstract document should fail."""
+        class Doc(Document):
+            name = StringField()
+            meta = {'abstract': True}
+
+        with self.assertRaises(InvalidDocumentError):
+            Doc(name='aaa').save()
+
     def test_reload(self):
         """Ensure that attributes may be reloaded.
         """