File tree Expand file tree Collapse file tree 3 files changed +56
-4
lines changed Expand file tree Collapse file tree 3 files changed +56
-4
lines changed Original file line number Diff line number Diff line change
1
+ import copy
2
+
3
+ from contextlib import contextmanager
4
+
5
+ from .manager import PostgresManager
6
+
7
+
8
+ @contextmanager
9
+ def postgres_manager (model ):
10
+ """Allows you to use the :see:PostgresManager with
11
+ the specified model instance on the fly.
12
+
13
+ Arguments:
14
+ model:
15
+ The model or model instance to use this on.
16
+ """
17
+
18
+ manager = PostgresManager ()
19
+ manager .model = model
20
+
21
+ yield manager
Original file line number Diff line number Diff line change 7
7
from psqlextra .models import PostgresModel
8
8
9
9
10
- def define_fake_model (fields = None ):
10
+ def define_fake_model (fields = None , model_base = PostgresModel ):
11
11
name = str (uuid .uuid4 ()).replace ('-' , '' )[:8 ]
12
12
13
13
attributes = {
@@ -18,15 +18,15 @@ def define_fake_model(fields=None):
18
18
19
19
if fields :
20
20
attributes .update (fields )
21
- model = type (name , (PostgresModel ,), attributes )
21
+ model = type (name , (model_base ,), attributes )
22
22
23
23
return model
24
24
25
25
26
- def get_fake_model (fields = None ):
26
+ def get_fake_model (fields = None , model_base = PostgresModel ):
27
27
"""Creates a fake model to use during unit tests."""
28
28
29
- model = define_fake_model (fields )
29
+ model = define_fake_model (fields , model_base )
30
30
31
31
class TestProject :
32
32
Original file line number Diff line number Diff line change
1
+ from django .db import models
2
+ from django .test import TestCase
3
+
4
+ from psqlextra .util import postgres_manager
5
+
6
+ from .fake_model import get_fake_model
7
+
8
+
9
+ class ManagerContextTestCase (TestCase ):
10
+ """Tests whether the :see:postgres_manager context
11
+ manager works properly."""
12
+
13
+ def test_manager_context (self ):
14
+ """Tests whether the :see:postgres_manager context
15
+ manager can be used to get access to :see:PostgresManager
16
+ on a model that does not use it directly or inherits
17
+ from :see:PostgresModel."""
18
+
19
+ model = get_fake_model ({
20
+ 'myfield' : models .CharField (max_length = 255 , unique = True )
21
+ }, models .Model )
22
+
23
+ with postgres_manager (model ) as manager :
24
+ manager .upsert (
25
+ conflict_target = ['myfield' ],
26
+ fields = dict (
27
+ myfield = 'beer'
28
+ )
29
+ )
30
+
31
+ assert manager .first ().myfield == 'beer'
You can’t perform that action at this time.
0 commit comments