pytest-neon 0.6.0__py3-none-any.whl → 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pytest_neon/__init__.py CHANGED
@@ -9,7 +9,7 @@ from pytest_neon.plugin import (
9
9
  neon_engine,
10
10
  )
11
11
 
12
- __version__ = "0.6.0"
12
+ __version__ = "2.0.0"
13
13
  __all__ = [
14
14
  "NeonBranch",
15
15
  "neon_branch",
pytest_neon/plugin.py CHANGED
@@ -5,15 +5,17 @@ instant branching feature. Each test gets a clean database state via
5
5
  branch reset after each test.
6
6
 
7
7
  Main fixtures:
8
- neon_branch: Primary fixture - one branch per session, reset after each test
9
- neon_branch_shared: Shared branch without reset (fastest, no isolation)
8
+ neon_branch_readwrite: Read-write access with reset after each test (recommended)
9
+ neon_branch_readonly: Read-only access, no reset (fastest for read-only tests)
10
+ neon_branch: Deprecated alias for neon_branch_readwrite
11
+ neon_branch_shared: Shared branch without reset (module-scoped)
10
12
  neon_connection: psycopg2 connection (requires psycopg2 extra)
11
13
  neon_connection_psycopg: psycopg v3 connection (requires psycopg extra)
12
14
  neon_engine: SQLAlchemy engine (requires sqlalchemy extra)
13
15
 
14
16
  SQLAlchemy Users:
15
17
  If you create your own SQLAlchemy engine (not using neon_engine fixture),
16
- you MUST use pool_pre_ping=True:
18
+ you MUST use pool_pre_ping=True when using neon_branch_readwrite:
17
19
 
18
20
  engine = create_engine(DATABASE_URL, pool_pre_ping=True)
19
21
 
@@ -21,6 +23,9 @@ SQLAlchemy Users:
21
23
  Without pool_pre_ping, SQLAlchemy may try to reuse dead pooled connections,
22
24
  causing "SSL connection has been closed unexpectedly" errors.
23
25
 
26
+ Note: pool_pre_ping is not required for neon_branch_readonly since no
27
+ resets occur.
28
+
24
29
  Configuration:
25
30
  Set NEON_API_KEY and NEON_PROJECT_ID environment variables, or use
26
31
  --neon-api-key and --neon-project-id CLI options.
@@ -33,6 +38,7 @@ from __future__ import annotations
33
38
  import contextlib
34
39
  import os
35
40
  import time
41
+ import warnings
36
42
  from collections.abc import Generator
37
43
  from dataclasses import dataclass
38
44
  from datetime import datetime, timedelta, timezone
@@ -373,8 +379,19 @@ def _create_neon_branch(
373
379
  )
374
380
 
375
381
 
376
- def _reset_branch_to_parent(branch: NeonBranch, api_key: str) -> None:
377
- """Reset a branch to its parent's state using the Neon API."""
382
+ def _reset_branch_to_parent(
383
+ branch: NeonBranch, api_key: str, max_retries: int = 3
384
+ ) -> None:
385
+ """Reset a branch to its parent's state using the Neon API.
386
+
387
+ Uses exponential backoff retry logic to handle transient API errors
388
+ that can occur during parallel test execution.
389
+
390
+ Args:
391
+ branch: The branch to reset
392
+ api_key: Neon API key
393
+ max_retries: Maximum number of retry attempts (default: 3)
394
+ """
378
395
  if not branch.parent_id:
379
396
  raise RuntimeError(f"Branch {branch.branch_id} has no parent - cannot reset")
380
397
 
@@ -383,10 +400,27 @@ def _reset_branch_to_parent(branch: NeonBranch, api_key: str) -> None:
383
400
  "Authorization": f"Bearer {api_key}",
384
401
  "Content-Type": "application/json",
385
402
  }
386
- response = requests.post(
387
- url, headers=headers, json={"source_branch_id": branch.parent_id}, timeout=30
388
- )
389
- response.raise_for_status()
403
+
404
+ last_error: Exception | None = None
405
+ for attempt in range(max_retries + 1):
406
+ try:
407
+ response = requests.post(
408
+ url,
409
+ headers=headers,
410
+ json={"source_branch_id": branch.parent_id},
411
+ timeout=30,
412
+ )
413
+ response.raise_for_status()
414
+ return # Success
415
+ except requests.RequestException as e:
416
+ last_error = e
417
+ if attempt < max_retries:
418
+ # Exponential backoff: 1s, 2s, 4s
419
+ wait_time = 2**attempt
420
+ time.sleep(wait_time)
421
+
422
+ # All retries exhausted
423
+ raise last_error # type: ignore[misc]
390
424
 
391
425
 
392
426
  @pytest.fixture(scope="session")
@@ -538,16 +572,21 @@ def _neon_branch_for_reset(
538
572
 
539
573
 
540
574
  @pytest.fixture(scope="function")
541
- def neon_branch(
575
+ def neon_branch_readwrite(
542
576
  request: pytest.FixtureRequest,
543
577
  _neon_branch_for_reset: NeonBranch,
544
578
  ) -> Generator[NeonBranch, None, None]:
545
579
  """
546
- Provide an isolated Neon database branch for each test.
580
+ Provide a read-write Neon database branch with reset after each test.
581
+
582
+ This is the recommended fixture for tests that modify database state.
583
+ It creates one branch per test session, then resets it to the parent
584
+ branch's state after each test. This provides test isolation with
585
+ ~0.5s overhead per test.
547
586
 
548
- This is the primary fixture for database testing. It creates one branch per
549
- test session, then resets it to the parent branch's state after each test.
550
- This provides test isolation with ~0.5s overhead per test.
587
+ Use this fixture when your tests INSERT, UPDATE, or DELETE data.
588
+ For read-only tests, use ``neon_branch_readonly`` instead for better
589
+ performance (no reset overhead).
551
590
 
552
591
  The branch is automatically deleted after all tests complete, unless
553
592
  --neon-keep-branches is specified. Branches also auto-expire after
@@ -575,11 +614,16 @@ def neon_branch(
575
614
 
576
615
  Example::
577
616
 
578
- def test_database_operation(neon_branch):
617
+ def test_insert_user(neon_branch_readwrite):
579
618
  # DATABASE_URL is automatically set
580
619
  conn_string = os.environ["DATABASE_URL"]
581
620
  # or use directly
582
- conn_string = neon_branch.connection_string
621
+ conn_string = neon_branch_readwrite.connection_string
622
+
623
+ # Insert data - branch will reset after this test
624
+ with psycopg.connect(conn_string) as conn:
625
+ conn.execute("INSERT INTO users (name) VALUES ('test')")
626
+ conn.commit()
583
627
  """
584
628
  config = request.config
585
629
  api_key = _get_config_value(config, "neon_api_key", "NEON_API_KEY", "neon_api_key")
@@ -588,8 +632,9 @@ def neon_branch(
588
632
  if not _neon_branch_for_reset.parent_id:
589
633
  pytest.fail(
590
634
  f"\n\nBranch {_neon_branch_for_reset.branch_id} has no parent. "
591
- f"The neon_branch fixture requires a parent branch for reset.\n\n"
592
- f"Use neon_branch_shared if you don't need reset, or specify "
635
+ f"The neon_branch_readwrite fixture requires a parent branch for "
636
+ f"reset.\n\n"
637
+ f"Use neon_branch_readonly if you don't need reset, or specify "
593
638
  f"a parent branch with --neon-parent-branch or NEON_PARENT_BRANCH_ID."
594
639
  )
595
640
 
@@ -608,6 +653,77 @@ def neon_branch(
608
653
  )
609
654
 
610
655
 
656
+ @pytest.fixture(scope="function")
657
+ def neon_branch_readonly(
658
+ _neon_branch_for_reset: NeonBranch,
659
+ ) -> NeonBranch:
660
+ """
661
+ Provide a read-only Neon database branch without reset.
662
+
663
+ This is the recommended fixture for tests that only read data (SELECT queries).
664
+ No branch reset occurs after each test, making it faster than
665
+ ``neon_branch_readwrite`` (~0.5s saved per test).
666
+
667
+ Use this fixture when your tests only perform SELECT queries and don't
668
+ modify database state. For tests that INSERT, UPDATE, or DELETE data,
669
+ use ``neon_branch_readwrite`` instead to ensure test isolation.
670
+
671
+ Warning:
672
+ If you accidentally write data using this fixture, subsequent tests
673
+ will see those modifications. The fixture does not enforce read-only
674
+ access at the database level - it simply skips the reset step.
675
+
676
+ The connection string is automatically set in the DATABASE_URL environment
677
+ variable (configurable via --neon-env-var).
678
+
679
+ Requires either:
680
+ - NEON_API_KEY and NEON_PROJECT_ID environment variables, or
681
+ - --neon-api-key and --neon-project-id command line options
682
+
683
+ Yields:
684
+ NeonBranch: Object with branch_id, project_id, connection_string, and host.
685
+
686
+ Example::
687
+
688
+ def test_query_users(neon_branch_readonly):
689
+ # DATABASE_URL is automatically set
690
+ conn_string = os.environ["DATABASE_URL"]
691
+
692
+ # Read-only query - no reset needed after this test
693
+ with psycopg.connect(conn_string) as conn:
694
+ result = conn.execute("SELECT * FROM users").fetchall()
695
+ assert len(result) > 0
696
+ """
697
+ return _neon_branch_for_reset
698
+
699
+
700
+ @pytest.fixture(scope="function")
701
+ def neon_branch(
702
+ request: pytest.FixtureRequest,
703
+ neon_branch_readwrite: NeonBranch,
704
+ ) -> Generator[NeonBranch, None, None]:
705
+ """
706
+ Deprecated: Use ``neon_branch_readwrite`` or ``neon_branch_readonly`` instead.
707
+
708
+ This fixture is an alias for ``neon_branch_readwrite`` and will be removed
709
+ in a future version. Please migrate to the explicit fixture names:
710
+
711
+ - ``neon_branch_readwrite``: For tests that modify data (INSERT/UPDATE/DELETE)
712
+ - ``neon_branch_readonly``: For tests that only read data (SELECT)
713
+
714
+ .. deprecated:: 1.1.0
715
+ Use ``neon_branch_readwrite`` for read-write access with reset,
716
+ or ``neon_branch_readonly`` for read-only access without reset.
717
+ """
718
+ warnings.warn(
719
+ "neon_branch is deprecated. Use neon_branch_readwrite (for tests that "
720
+ "modify data) or neon_branch_readonly (for read-only tests) instead.",
721
+ DeprecationWarning,
722
+ stacklevel=2,
723
+ )
724
+ yield neon_branch_readwrite
725
+
726
+
611
727
  @pytest.fixture(scope="module")
612
728
  def neon_branch_shared(
613
729
  request: pytest.FixtureRequest,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytest-neon
3
- Version: 0.6.0
3
+ Version: 2.0.0
4
4
  Summary: Pytest plugin for Neon database branch isolation in tests
5
5
  Project-URL: Homepage, https://github.com/ZainRizvi/pytest-neon
6
6
  Project-URL: Repository, https://github.com/ZainRizvi/pytest-neon
@@ -97,7 +97,7 @@ export NEON_PROJECT_ID="your-project-id"
97
97
  2. Write tests:
98
98
 
99
99
  ```python
100
- def test_user_creation(neon_branch):
100
+ def test_user_creation(neon_branch_readwrite):
101
101
  # DATABASE_URL is automatically set to the test branch
102
102
  import psycopg # Your own install
103
103
 
@@ -105,6 +105,7 @@ def test_user_creation(neon_branch):
105
105
  with conn.cursor() as cur:
106
106
  cur.execute("INSERT INTO users (email) VALUES ('test@example.com')")
107
107
  conn.commit()
108
+ # Branch automatically resets after test - next test sees clean state
108
109
  ```
109
110
 
110
111
  3. Run tests:
@@ -115,33 +116,75 @@ pytest
115
116
 
116
117
  ## Fixtures
117
118
 
118
- ### `neon_branch` (default, recommended)
119
+ **Which fixture should I use?**
119
120
 
120
- The primary fixture for database testing. Creates one branch per test session, then resets it to the parent branch's state after each test. This provides test isolation with ~0.5s overhead per test.
121
+ - **Use `neon_branch_readonly`** if your test only reads data (SELECT queries). This is the fastest option with no per-test overhead.
122
+ - **Use `neon_branch_readwrite`** if your test modifies data (INSERT, UPDATE, DELETE). This resets the branch after each test for isolation.
121
123
 
122
- Returns a `NeonBranch` dataclass with:
124
+ ### `neon_branch_readonly` (recommended, fastest)
123
125
 
124
- - `branch_id`: The Neon branch ID
125
- - `project_id`: The Neon project ID
126
- - `connection_string`: Full PostgreSQL connection URI
127
- - `host`: The database host
128
- - `parent_id`: The parent branch ID (used for resets)
126
+ **Use this fixture by default** if your tests don't need to write data. It provides the best performance by skipping the branch reset step (~0.5s saved per test), which also reduces API calls and avoids rate limiting issues.
127
+
128
+ ```python
129
+ def test_query_users(neon_branch_readonly):
130
+ # DATABASE_URL is set automatically
131
+ import psycopg
132
+ with psycopg.connect(neon_branch_readonly.connection_string) as conn:
133
+ result = conn.execute("SELECT * FROM users").fetchall()
134
+ assert len(result) >= 0
135
+ # No reset after this test - fast!
136
+ ```
137
+
138
+ **Use this when**:
139
+ - Tests only perform SELECT queries
140
+ - Tests don't modify database state
141
+ - You want maximum performance
142
+
143
+ **Warning**: If you accidentally write data using this fixture, subsequent tests will see those modifications. The fixture does not enforce read-only access at the database level.
144
+
145
+ **Performance**: ~1.5s initial setup per session, **no per-test overhead**. For 10 read-only tests, expect only ~1.5s total overhead (vs ~6.5s with readwrite).
146
+
147
+ ### `neon_branch_readwrite` (for write tests)
148
+
149
+ Use this fixture when your tests need to INSERT, UPDATE, or DELETE data. Creates one branch per test session, then resets it to the parent branch's state after each test. This provides test isolation with ~0.5s overhead per test.
129
150
 
130
151
  ```python
131
152
  import os
132
153
 
133
- def test_branch_info(neon_branch):
154
+ def test_insert_user(neon_branch_readwrite):
134
155
  # DATABASE_URL is set automatically
135
- assert os.environ["DATABASE_URL"] == neon_branch.connection_string
156
+ assert os.environ["DATABASE_URL"] == neon_branch_readwrite.connection_string
136
157
 
137
158
  # Use with any driver
138
159
  import psycopg
139
- conn = psycopg.connect(neon_branch.connection_string)
160
+ with psycopg.connect(neon_branch_readwrite.connection_string) as conn:
161
+ conn.execute("INSERT INTO users (name) VALUES ('test')")
162
+ conn.commit()
163
+ # Branch resets after this test - changes won't affect other tests
140
164
  ```
141
165
 
142
- **Performance**: ~1.5s initial setup per session + ~0.5s reset per test. For 10 tests, expect ~6.5s total overhead.
166
+ **Performance**: ~1.5s initial setup per session + ~0.5s reset per test. For 10 write tests, expect ~6.5s total overhead.
143
167
 
144
- ### `neon_branch_shared` (fastest, no isolation)
168
+ ### `NeonBranch` dataclass
169
+
170
+ Both fixtures return a `NeonBranch` dataclass with:
171
+
172
+ - `branch_id`: The Neon branch ID
173
+ - `project_id`: The Neon project ID
174
+ - `connection_string`: Full PostgreSQL connection URI
175
+ - `host`: The database host
176
+ - `parent_id`: The parent branch ID (used for resets)
177
+
178
+ ### `neon_branch` (deprecated)
179
+
180
+ > **Deprecated**: Use `neon_branch_readwrite` or `neon_branch_readonly` instead.
181
+
182
+ This fixture is an alias for `neon_branch_readwrite` and will emit a deprecation warning. Migrate to the explicit fixture names for clarity:
183
+
184
+ - `neon_branch_readwrite`: For tests that modify data (INSERT/UPDATE/DELETE)
185
+ - `neon_branch_readonly`: For tests that only read data (SELECT)
186
+
187
+ ### `neon_branch_shared` (module-scoped, no isolation)
145
188
 
146
189
  Creates one branch per test module and shares it across all tests without resetting. This is the fastest option but tests can see each other's data modifications.
147
190
 
@@ -207,19 +250,21 @@ def test_query(neon_engine):
207
250
 
208
251
  ### Using Your Own SQLAlchemy Engine
209
252
 
210
- If you have a module-level SQLAlchemy engine (common pattern), you **must** use `pool_pre_ping=True`:
253
+ If you have a module-level SQLAlchemy engine (common pattern) and use `neon_branch_readwrite`, you **must** use `pool_pre_ping=True`:
211
254
 
212
255
  ```python
213
256
  # database.py
214
257
  from sqlalchemy import create_engine
215
258
  from config import DATABASE_URL
216
259
 
217
- # pool_pre_ping=True is REQUIRED for pytest-neon
260
+ # pool_pre_ping=True is REQUIRED when using neon_branch_readwrite
218
261
  # It verifies connections are alive before using them
219
262
  engine = create_engine(DATABASE_URL, pool_pre_ping=True)
220
263
  ```
221
264
 
222
- **Why?** After each test, pytest-neon resets the branch which terminates server-side connections. Without `pool_pre_ping`, SQLAlchemy may try to reuse a dead pooled connection, causing `SSL connection has been closed unexpectedly` errors.
265
+ **Why?** After each test, `neon_branch_readwrite` resets the branch which terminates server-side connections. Without `pool_pre_ping`, SQLAlchemy may try to reuse a dead pooled connection, causing `SSL connection has been closed unexpectedly` errors.
266
+
267
+ **Note**: If you only use `neon_branch_readonly`, `pool_pre_ping` is not required since no resets occur.
223
268
 
224
269
  This is also a best practice for any cloud database (Neon, RDS, etc.) where connections can be terminated externally.
225
270
 
@@ -435,7 +480,7 @@ Branches use copy-on-write storage, so you only pay for data that differs from t
435
480
 
436
481
  ### What Reset Does
437
482
 
438
- The `neon_branch` fixture uses Neon's branch restore API to reset database state after each test:
483
+ The `neon_branch_readwrite` fixture uses Neon's branch restore API to reset database state after each test:
439
484
 
440
485
  - **Data changes are reverted**: All INSERT, UPDATE, DELETE operations are undone
441
486
  - **Schema changes are reverted**: CREATE TABLE, ALTER TABLE, DROP TABLE, etc. are undone
@@ -472,12 +517,12 @@ pip install pytest-neon[psycopg2]
472
517
  pip install pytest-neon[sqlalchemy]
473
518
  ```
474
519
 
475
- Or use the core `neon_branch` fixture with your own driver:
520
+ Or use the core fixtures with your own driver:
476
521
 
477
522
  ```python
478
- def test_example(neon_branch):
523
+ def test_example(neon_branch_readwrite):
479
524
  import my_preferred_driver
480
- conn = my_preferred_driver.connect(neon_branch.connection_string)
525
+ conn = my_preferred_driver.connect(neon_branch_readwrite.connection_string)
481
526
  ```
482
527
 
483
528
  ### "Neon API key not configured"
@@ -0,0 +1,8 @@
1
+ pytest_neon/__init__.py,sha256=Ti_bjX7CgEZjtaY_uoNnkSvRUXnEw4MkfsbFie_K6Mo,398
2
+ pytest_neon/plugin.py,sha256=9VH7h2UYp0AoJj3FagpP6Xqtd1_qqkcuS0sLF-cqYpo,33877
3
+ pytest_neon/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ pytest_neon-2.0.0.dist-info/METADATA,sha256=bQ7y0oOcymrho3AY9NhHRFT1FNM4jPK27rRFh217FN4,18386
5
+ pytest_neon-2.0.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
6
+ pytest_neon-2.0.0.dist-info/entry_points.txt,sha256=5U88Idj_G8-PSDb9VF3OwYFbGLHnGOo_GxgYvi0dtXw,37
7
+ pytest_neon-2.0.0.dist-info/licenses/LICENSE,sha256=aKKp_Ex4WBHTByY4BhXJ181dzB_qYhi2pCUmZ7Spn_0,1067
8
+ pytest_neon-2.0.0.dist-info/RECORD,,
@@ -1,8 +0,0 @@
1
- pytest_neon/__init__.py,sha256=54UgijfJx44ra6-LyAS2fKVPTdqOKofrD3wQeCt8ydQ,398
2
- pytest_neon/plugin.py,sha256=6wcZe9E90y2kya4wM0ur9EtUhqWFUll_ebN4xgsogPk,29601
3
- pytest_neon/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- pytest_neon-0.6.0.dist-info/METADATA,sha256=Aw8Y8MHYAo9Wt8TbthiN-pd8pAQenaHckwobPipvtsk,16057
5
- pytest_neon-0.6.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
6
- pytest_neon-0.6.0.dist-info/entry_points.txt,sha256=5U88Idj_G8-PSDb9VF3OwYFbGLHnGOo_GxgYvi0dtXw,37
7
- pytest_neon-0.6.0.dist-info/licenses/LICENSE,sha256=aKKp_Ex4WBHTByY4BhXJ181dzB_qYhi2pCUmZ7Spn_0,1067
8
- pytest_neon-0.6.0.dist-info/RECORD,,