-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdk-python.html
More file actions
535 lines (466 loc) · 20.6 KB
/
sdk-python.html
File metadata and controls
535 lines (466 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-5C3LL34WWW"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-5C3LL34WWW');
</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python SDK - Local Web Services</title>
<meta name="description" content="local-web-services-python-sdk: in-process AWS service testing for Python. pytest fixtures, DynamoDB/SQS/S3 helpers, faking, chaos, IAM, and log capture.">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css">
</head>
<body>
<nav class="nav">
<div class="container nav-inner">
<a href="index.html" class="nav-logo">Local Web Services</a>
<ul class="nav-links">
<li><a href="getting-started.html">Get Started</a></li>
<li><a href="sdks.html" class="nav-active">SDKs</a></li>
<li><a href="services.html">Cloud Emulation</a></li>
<li><a href="faking.html">Faking Services</a></li>
<li><a href="chaos.html">Chaos Engineering</a></li>
<li><a href="cli.html">CLI</a></li>
<li><a href="https://github.com/local-web-services/local-web-services" class="nav-github">GitHub</a></li>
</ul>
</div>
</nav>
<header class="page-header">
<div class="container">
<h1>Python SDK</h1>
<p class="section-lead">In-process AWS service testing for pytest. Use your existing boto3 code unchanged — the SDK provides pre-configured clients that point to local services instead of AWS. No credentials, no deploy, no waiting.</p>
<div style="display: flex; gap: 16px; justify-content: center; margin-top: 24px; flex-wrap: wrap;">
<a href="https://pypi.org/project/local-web-services-python-sdk/" class="btn btn-primary">PyPI</a>
<a href="https://github.com/local-web-services/local-web-services/tree/main/lang/python/sdk" class="btn btn-secondary">GitHub</a>
<a href="https://github.com/local-web-services/local-web-services/tree/main/lang/python/example" class="btn btn-secondary">Example Project</a>
<a href="sdks.html" class="btn btn-secondary">All SDKs</a>
</div>
</div>
</header>
<!-- Quick Start -->
<section class="section">
<div class="container">
<h2>Quick Start</h2>
<p class="section-lead">Install, declare your resources, and write a test. Services start in the same process as your tests — no external server, no ports, no Docker.</p>
<div class="steps" style="max-width: 900px;">
<div class="step">
<div class="step-number">1</div>
<div class="step-content">
<h3>Install</h3>
<div class="code-block">
<code>pip install local-web-services-python-sdk
# or
uv add local-web-services-python-sdk</code>
</div>
</div>
</div>
<div class="step">
<div class="step-number">2</div>
<div class="step-content">
<h3>Configure pytest fixtures in conftest.py</h3>
<div class="code-block">
<code># conftest.py
import pytest
@pytest.fixture(scope="session")
def lws_session_spec():
return {
"tables": [{"name": "Orders", "partition_key": "id"}],
"queues": ["OrderQueue"],
"buckets": ["ReceiptsBucket"],
}
# lws_session and lws_reset are provided automatically
# by the lws_testing pytest plugin — no imports needed</code>
</div>
</div>
</div>
<div class="step">
<div class="step-number">3</div>
<div class="step-content">
<h3>Write your test</h3>
<div class="code-block">
<code># test_orders.py
def test_create_order(lws_session):
# Call your real application code
from myapp.orders import create_order
create_order(order_id="42", status="pending")
# Assert on local DynamoDB with the helper
table = lws_session.dynamodb("Orders")
table.assert_item_exists({"id": {"S": "42"}})
def test_order_sends_queue_message(lws_session):
from myapp.orders import create_order
create_order(order_id="99", status="pending")
queue = lws_session.sqs("OrderQueue")
queue.assert_message_count(1)</code>
</div>
</div>
</div>
<div class="step">
<div class="step-number">4</div>
<div class="step-content">
<h3>Run your tests</h3>
<div class="code-block">
<code>pytest</code>
</div>
<p style="margin-top: 12px; color: var(--color-text-muted);">Services start once per session. State is wiped between tests automatically by the <code>lws_reset</code> fixture.</p>
</div>
</div>
</div>
</div>
</section>
<!-- Drop-in replacement -->
<section class="section section-alt">
<div class="container">
<h2>Drop-in Replacement — Zero Code Changes</h2>
<p class="section-lead">Your application code already uses boto3. The SDK returns standard boto3 clients pre-configured to talk to local services. Nothing in your application needs to change.</p>
<div class="comparison comparison--code">
<div class="comparison-col">
<h3>Your application code</h3>
<div class="code-block" style="margin-top: 16px;">
<code># myapp/orders.py — unchanged
import boto3, os
def create_order(order_id: str, status: str):
client = boto3.client("dynamodb")
client.put_item(
TableName="Orders",
Item={
"id": {"S": order_id},
"status": {"S": status},
},
)
sqs = boto3.client("sqs")
sqs.send_message(
QueueUrl=os.environ["ORDER_QUEUE_URL"],
MessageBody=order_id,
)</code>
</div>
</div>
<div class="comparison-col">
<h3>Your test</h3>
<div class="code-block" style="margin-top: 16px;">
<code># test_orders.py
def test_create_order(lws_session):
# The SDK patches the boto3 endpoint for you.
# Application code runs exactly as written.
from myapp.orders import create_order
create_order("42", "pending")
table = lws_session.dynamodb("Orders")
table.assert_item_exists({"id": {"S": "42"}})
queue = lws_session.sqs("OrderQueue")
queue.assert_message_count(1)</code>
</div>
</div>
</div>
<div class="feature-grid" style="margin-top: 48px;">
<div class="feature-card">
<div class="feature-icon">🔓</div>
<h3>No Credentials</h3>
<p>Local services accept any credentials. No AWS account, no IAM users, no <code>~/.aws/credentials</code> required.</p>
</div>
<div class="feature-card">
<div class="feature-icon">∅</div>
<h3>No Refactoring</h3>
<p>Application code stays identical to production. The SDK redirects boto3 to local endpoints at test time — no dependency injection required.</p>
</div>
<div class="feature-card">
<div class="feature-icon">⚡</div>
<h3>No External Process</h3>
<p>Services run as threads inside your test process. No Docker, no ports, no startup scripts. Tests begin in milliseconds.</p>
</div>
</div>
</div>
</section>
<!-- pytest Fixtures -->
<section class="section">
<div class="container">
<h2>pytest Integration</h2>
<p class="section-lead">The SDK registers pytest fixtures automatically via a <code>pytest11</code> entry point. No imports needed in your conftest — just define a session spec fixture.</p>
<div class="lws-command-grid" style="margin-top: 0;">
<div class="lws-command">
<h4>lws_session</h4>
<p>Session-scoped <code>LwsSession</code> instance. Configure via <code>lws_session_spec</code> fixture. Services start once and are reused across all tests.</p>
</div>
<div class="lws-command">
<h4>lws_reset</h4>
<p>Function-scoped autouse fixture. Calls <code>session.reset()</code> before each test to wipe all DynamoDB tables, SQS queues, and S3 buckets. Enabled automatically.</p>
</div>
<div class="lws-command">
<h4>lws_session_from_cdk</h4>
<p>Session-scoped session with auto-discovery from CDK project. Configure path via <code>cdk_project_dir</code> fixture (default <code>"."</code>).</p>
</div>
<div class="lws-command">
<h4>lws_session_from_hcl</h4>
<p>Session-scoped session with auto-discovery from HCL project. Configure path via <code>hcl_project_dir</code> fixture (default <code>"."</code>).</p>
</div>
</div>
<div class="code-block config-example" style="margin-top: 32px;">
<code># conftest.py
import pytest
@pytest.fixture(scope="session")
def lws_session_spec():
return {
"tables": [
{"name": "Orders", "partition_key": "id"},
{"name": "Products", "partition_key": "sku", "sort_key": "version"},
],
"queues": ["OrderQueue", "DeadLetterQueue"],
"buckets": ["ReceiptsBucket"],
"secrets": [{"name": "stripe-key", "value": "sk_test_..."}],
"parameters": [{"name": "/app/config", "value": "test"}],
}</code>
</div>
</div>
</section>
<!-- Resource Helpers -->
<section class="section section-alt">
<div class="container">
<h2>Resource Helpers</h2>
<p class="section-lead">Simplified wrappers with built-in assertions. No more writing <code>assert response['Item']['id']['S'] == '42'</code>.</p>
<h3 class="section-subheading section-subheading--primary">DynamoDB</h3>
<div class="code-block config-example">
<code>table = session.dynamodb("Orders")
table.put({"id": {"S": "1"}, "status": {"S": "pending"}})
item = table.get({"id": {"S": "1"}})
table.delete({"id": {"S": "1"}})
items = table.scan()
table.assert_item_exists({"id": {"S": "1"}})
table.assert_item_count(5)</code>
</div>
<h3 class="section-subheading section-subheading--primary">SQS</h3>
<div class="code-block config-example">
<code>queue = session.sqs("OrderQueue")
queue.send({"orderId": "42", "total": 99.99}) # dict → JSON
queue.send("plain text message") # or raw string
messages = queue.receive(max_messages=10)
queue.purge()
queue.assert_message_count(3)
print(queue.url) # http://localhost:.../OrderQueue</code>
</div>
<h3 class="section-subheading section-subheading--primary">S3</h3>
<div class="code-block config-example">
<code>bucket = session.s3("ReceiptsBucket")
bucket.put("receipts/001.pdf", b"PDF bytes")
bucket.put("config.json", '{"key": "value"}') # auto-encodes
data = bucket.get("receipts/001.pdf") # bytes
text = bucket.get_text("config.json") # string
keys = bucket.list_keys(prefix="receipts/")
bucket.delete("config.json")
bucket.assert_object_exists("receipts/001.pdf")
bucket.assert_object_count(expected_count=5, prefix="receipts/")</code>
</div>
</div>
</section>
<!-- LwsSession -->
<section class="section">
<div class="container">
<h2>LwsSession</h2>
<p class="section-lead">Use directly as a context manager, or let the pytest fixtures manage the lifecycle for you.</p>
<h3 class="section-subheading section-subheading--primary">Explicit resource declaration</h3>
<div class="code-block config-example">
<code>from lws_testing import LwsSession
with LwsSession(
tables=[{"name": "Orders", "partition_key": "id"}],
queues=["OrderQueue"],
buckets=["ReceiptsBucket"],
topics=[{"name": "OrderEvents", "arn": "arn:aws:sns:us-east-1:000000000000:OrderEvents"}],
state_machines=[{"name": "OrderWorkflow", "definition": {...}}],
secrets=[{"name": "stripe-key", "value": "sk_test_..."}],
parameters=[{"name": "/app/config", "value": "production"}],
) as session:
client = session.client("dynamodb")
client.put_item(TableName="Orders", Item={"id": {"S": "1"}})</code>
</div>
<h3 class="section-subheading section-subheading--primary">Auto-discover from CDK or HCL</h3>
<div class="code-block config-example">
<code>from lws_testing import LwsSession
# Reads cdk.out/ cloud assembly
with LwsSession.from_cdk("../my-cdk-project") as session:
dynamo = session.client("dynamodb")
# Reads .tf files
with LwsSession.from_hcl("../my-terraform-project") as session:
s3 = session.client("s3")</code>
</div>
<h3 class="section-subheading section-subheading--primary">Available services</h3>
<div class="code-block config-example">
<code>session.client("dynamodb")
session.client("sqs")
session.client("s3")
session.client("sns")
session.client("ssm")
session.client("secretsmanager")
session.client("stepfunctions")
session.reset() # clear all tables, queues, buckets</code>
</div>
</div>
</section>
<!-- Faking -->
<section class="section section-alt">
<div class="container">
<h2>Operation Faking</h2>
<p class="section-lead">Override specific AWS operation responses with a fluent builder. Inject throttling errors, custom status codes, or delays without changing application code.</p>
<div class="code-block config-example">
<code># Inject a throttling error
session.fake("dynamodb").operation("PutItem").respond(
status=400,
body={"__type": "ProvisionedThroughputExceededException"},
)
# Add artificial latency
session.fake("sqs").operation("SendMessage").respond(status=200, delay_ms=500)
# Match on a specific request header
session.fake("s3")\
.operation("GetObject")\
.with_header("x-request-id", "test-123")\
.respond(status=403, body={"__type": "AccessDenied"})
# Shorthand for service errors
session.fake("dynamodb").operation("DeleteItem").error(
error_type="ValidationException",
message="Item not found",
)
session.fake("dynamodb").clear() # remove all fakes for a service</code>
</div>
<div class="code-block config-example">
<code>def test_handles_throttling(lws_session):
lws_session.fake("dynamodb").operation("PutItem").respond(
status=400,
body={"__type": "ProvisionedThroughputExceededException"},
)
with pytest.raises(ClientError) as exc:
from myapp.orders import create_order
create_order("42", "pending")
assert "ProvisionedThroughputExceededException" in str(exc.value)
lws_session.fake("dynamodb").clear()</code>
</div>
</div>
</section>
<!-- Chaos Engineering -->
<section class="section">
<div class="container">
<h2>Chaos Engineering</h2>
<p class="section-lead">Inject error rates, latency, connection resets, and timeouts into any service to verify your application's resilience.</p>
<div class="code-block config-example">
<code>session.chaos("dynamodb").error_rate(0.3).latency(min_ms=50, max_ms=200).apply()
session.chaos("sqs").connection_reset_rate(0.1).timeout_rate(0.05).apply()
session.chaos("dynamodb").clear()</code>
</div>
<div class="code-block config-example">
<code>def test_resilient_to_latency(lws_session):
lws_session.chaos("dynamodb").latency(min_ms=100, max_ms=500).apply()
import time
start = time.time()
from myapp.orders import create_order
create_order("42", "pending")
elapsed = time.time() - start
assert elapsed >= 0.1 # latency was injected
lws_session.chaos("dynamodb").clear()</code>
</div>
</div>
</section>
<!-- IAM Authorization -->
<section class="section section-alt">
<div class="container">
<h2>IAM Authorization</h2>
<p class="section-lead">Test that your application enforces least-privilege access correctly by switching IAM modes and defining named identities.</p>
<div class="code-block config-example">
<code>session.iam.mode("enforce").apply() # HTTP 403 on policy violation
session.iam.mode("audit").apply() # log violations, allow requests
session.iam.mode("disabled").apply() # no checks (default)
session.iam.default_identity("service-account").apply()
session.iam\
.identity("readonly")\
.allow(["dynamodb:GetItem", "dynamodb:Scan"])\
.apply()
session.iam\
.identity("restricted")\
.allow(["s3:GetObject"], resource="arn:aws:s3:::my-bucket/*")\
.deny(["s3:DeleteObject"])\
.boundary(["s3:*"], resource="*")\
.apply()</code>
</div>
</div>
</section>
<!-- Log Capture -->
<section class="section">
<div class="container">
<h2>Log Capture</h2>
<p class="section-lead">Verify exactly which AWS service calls your application made — and that no unexpected calls or errors occurred.</p>
<div class="code-block config-example">
<code>def test_service_calls(lws_session):
with lws_session.capture_logs() as logs:
from myapp.orders import create_order
create_order(order_id="123")
logs.assert_called("dynamodb", "PutItem")
logs.assert_called("sqs", "SendMessage")
logs.assert_call_count("dynamodb", "Scan", expected_count=0)
logs.assert_not_called("s3", "GetObject")
logs.assert_no_errors()</code>
</div>
</div>
</section>
<!-- Resource Discovery -->
<section class="section section-alt">
<div class="container">
<h2>Resource Discovery</h2>
<p class="section-lead">Instead of declaring resources manually, let the SDK discover them from your CDK cloud assembly or HCL files.</p>
<div class="feature-grid feature-grid--2col">
<div class="feature-card">
<div class="feature-icon">☁️</div>
<h3>CDK Discovery</h3>
<p>Reads <code>cdk.out/</code> from <code>cdk synth</code>. Discovers DynamoDB tables, SQS queues, S3 buckets, SNS topics, Step Functions, SSM parameters, and Secrets Manager secrets.</p>
<div class="code-block" style="margin-top: 16px;">
<code>LwsSession.from_cdk("../my-cdk-project")</code>
</div>
</div>
<div class="feature-card">
<div class="feature-icon">🔧</div>
<h3>HCL Discovery</h3>
<p>Parses <code>.tf</code> files in your project directory. No <code>terraform plan</code> or <code>terraform apply</code> needed.</p>
<div class="code-block" style="margin-top: 16px;">
<code>LwsSession.from_hcl("../my-terraform-project")</code>
</div>
</div>
</div>
<div class="code-block config-example" style="margin-top: 32px;">
<code># Override the project directory via a pytest fixture
# conftest.py
@pytest.fixture(scope="session")
def cdk_project_dir():
return "../my-cdk-app"
# Then use lws_session_from_cdk in your tests directly
def test_with_cdk_resources(lws_session_from_cdk):
table = lws_session_from_cdk.dynamodb("MyTable")
table.assert_item_count(0)</code>
</div>
</div>
</section>
<footer class="footer">
<div class="container">
<div class="footer-inner">
<div class="footer-brand">
<a href="index.html" class="nav-logo">Local Web Services</a>
<p>The fastest feedback loop for cloud-native development, for humans and AI alike</p>
</div>
<div class="footer-links">
<a href="https://github.com/local-web-services/local-web-services">GitHub</a>
<a href="https://github.com/local-web-services/local-web-services/tree/main/lang/python/sdk">Python SDK</a>
<a href="https://pypi.org/project/local-web-services-python-sdk/">PyPI</a>
<a href="https://github.com/local-web-services/local-web-services/tree/main/sample-project/cdk">CDK Sample</a>
<a href="https://github.com/local-web-services/local-web-services/tree/main/sample-project/hcl">Terraform Sample</a>
<a href="https://github.com/local-web-services/local-web-services/issues">Issues</a>
</div>
</div>
<p class="footer-copy">Open source under the MIT License.</p>
</div>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-clike.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-bash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-yaml.min.js"></script>
<script src="lws.js"></script>
</body>
</html>