-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathchapter_05_high_gear_low_gear.html
898 lines (833 loc) · 56.7 KB
/
chapter_05_high_gear_low_gear.html
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 2.0.20">
<title>TDD in High Gear and Low Gear</title>
<style>
/* Asciidoctor default stylesheet | MIT License | https://asciidoctor.org */
@import url("//fonts.googleapis.com/css?family=Noto+Sans:300,600italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700");
@import url(//asciidoctor.org/stylesheets/asciidoctor.css); /* Default asciidoc style framework - important */
/* customisations by harry */
h1, h2, h3, h4, h5, h6 {
position: relative;
}
a.anchor {
top: 0;
}
/* hide inline ditaa/plantuml source listings for images */
.image-source {
display: none
}
/* make formal codeblocks a bit nicer */
.exampleblock > .content {
padding: 2px;
background-color: white;
border: 0;
margin-bottom: 2em;
}
.exampleblock .title {
text-align: right;
}
/* prev/next chapter links at bottom of page */
.prev_and_next_chapter_links {
margin: 10px;
}
.prev_chapter_link {
float: left;
}
.next_chapter_link {
float: right;
}
/* a few tweaks to existing styles */
#toc li {
margin-top: 0.5em;
}
#footnotes hr {
width: 100%;
}
/* end customisations by harry */
/* CUSTOMISATIONS */
/* Change the values in root for quick customisation. If you want even more fine grain... venture further. */
:root{
--maincolor:#FFFFFF;
--primarycolor:#2c3e50;
--secondarycolor:#ba3925;
--tertiarycolor: #186d7a;
--sidebarbackground:#CCC;
--linkcolor:#b71c1c;
--linkcoloralternate:#f44336;
--white:#FFFFFF;
--black:#000000;
}
/* Text styles */
h1{color:var(--primarycolor) !important;}
h2,h3,h4,h5,h6{color:var(--secondarycolor) !important;}
.title{color:var(--tertiarycolor) !important; font-family:"Noto Sans",sans-serif !important;font-style: normal !important; font-weight: normal !important;}
p{font-family: "Noto Sans",sans-serif !important}
/* Table styles */
th{font-family: "Noto Sans",sans-serif !important}
/* Responsiveness fixes */
video {
max-width: 100%;
}
@media all and (max-width: 600px) {
table {
width: 55vw!important;
font-size: 3vw;
}
</style>
<style>
pre.pygments .hll { background-color: #ffffcc }
pre.pygments { background: #f0f0f0; }
pre.pygments .tok-c { color: #60a0b0; font-style: italic } /* Comment */
pre.pygments .tok-err { border: 1px solid #FF0000 } /* Error */
pre.pygments .tok-k { color: #007020; font-weight: bold } /* Keyword */
pre.pygments .tok-o { color: #666666 } /* Operator */
pre.pygments .tok-ch { color: #60a0b0; font-style: italic } /* Comment.Hashbang */
pre.pygments .tok-cm { color: #60a0b0; font-style: italic } /* Comment.Multiline */
pre.pygments .tok-cp { color: #007020 } /* Comment.Preproc */
pre.pygments .tok-cpf { color: #60a0b0; font-style: italic } /* Comment.PreprocFile */
pre.pygments .tok-c1 { color: #60a0b0; font-style: italic } /* Comment.Single */
pre.pygments .tok-cs { color: #60a0b0; background-color: #fff0f0 } /* Comment.Special */
pre.pygments .tok-gd { color: #A00000 } /* Generic.Deleted */
pre.pygments .tok-ge { font-style: italic } /* Generic.Emph */
pre.pygments .tok-gr { color: #FF0000 } /* Generic.Error */
pre.pygments .tok-gh { color: #000080; font-weight: bold } /* Generic.Heading */
pre.pygments .tok-gi { color: #00A000 } /* Generic.Inserted */
pre.pygments .tok-go { color: #888888 } /* Generic.Output */
pre.pygments .tok-gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */
pre.pygments .tok-gs { font-weight: bold } /* Generic.Strong */
pre.pygments .tok-gu { color: #800080; font-weight: bold } /* Generic.Subheading */
pre.pygments .tok-gt { color: #0044DD } /* Generic.Traceback */
pre.pygments .tok-kc { color: #007020; font-weight: bold } /* Keyword.Constant */
pre.pygments .tok-kd { color: #007020; font-weight: bold } /* Keyword.Declaration */
pre.pygments .tok-kn { color: #007020; font-weight: bold } /* Keyword.Namespace */
pre.pygments .tok-kp { color: #007020 } /* Keyword.Pseudo */
pre.pygments .tok-kr { color: #007020; font-weight: bold } /* Keyword.Reserved */
pre.pygments .tok-kt { color: #902000 } /* Keyword.Type */
pre.pygments .tok-m { color: #40a070 } /* Literal.Number */
pre.pygments .tok-s { color: #4070a0 } /* Literal.String */
pre.pygments .tok-na { color: #4070a0 } /* Name.Attribute */
pre.pygments .tok-nb { color: #007020 } /* Name.Builtin */
pre.pygments .tok-nc { color: #0e84b5; font-weight: bold } /* Name.Class */
pre.pygments .tok-no { color: #60add5 } /* Name.Constant */
pre.pygments .tok-nd { color: #555555; font-weight: bold } /* Name.Decorator */
pre.pygments .tok-ni { color: #d55537; font-weight: bold } /* Name.Entity */
pre.pygments .tok-ne { color: #007020 } /* Name.Exception */
pre.pygments .tok-nf { color: #06287e } /* Name.Function */
pre.pygments .tok-nl { color: #002070; font-weight: bold } /* Name.Label */
pre.pygments .tok-nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */
pre.pygments .tok-nt { color: #062873; font-weight: bold } /* Name.Tag */
pre.pygments .tok-nv { color: #bb60d5 } /* Name.Variable */
pre.pygments .tok-ow { color: #007020; font-weight: bold } /* Operator.Word */
pre.pygments .tok-w { color: #bbbbbb } /* Text.Whitespace */
pre.pygments .tok-mb { color: #40a070 } /* Literal.Number.Bin */
pre.pygments .tok-mf { color: #40a070 } /* Literal.Number.Float */
pre.pygments .tok-mh { color: #40a070 } /* Literal.Number.Hex */
pre.pygments .tok-mi { color: #40a070 } /* Literal.Number.Integer */
pre.pygments .tok-mo { color: #40a070 } /* Literal.Number.Oct */
pre.pygments .tok-sa { color: #4070a0 } /* Literal.String.Affix */
pre.pygments .tok-sb { color: #4070a0 } /* Literal.String.Backtick */
pre.pygments .tok-sc { color: #4070a0 } /* Literal.String.Char */
pre.pygments .tok-dl { color: #4070a0 } /* Literal.String.Delimiter */
pre.pygments .tok-sd { color: #4070a0; font-style: italic } /* Literal.String.Doc */
pre.pygments .tok-s2 { color: #4070a0 } /* Literal.String.Double */
pre.pygments .tok-se { color: #4070a0; font-weight: bold } /* Literal.String.Escape */
pre.pygments .tok-sh { color: #4070a0 } /* Literal.String.Heredoc */
pre.pygments .tok-si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */
pre.pygments .tok-sx { color: #c65d09 } /* Literal.String.Other */
pre.pygments .tok-sr { color: #235388 } /* Literal.String.Regex */
pre.pygments .tok-s1 { color: #4070a0 } /* Literal.String.Single */
pre.pygments .tok-ss { color: #517918 } /* Literal.String.Symbol */
pre.pygments .tok-bp { color: #007020 } /* Name.Builtin.Pseudo */
pre.pygments .tok-fm { color: #06287e } /* Name.Function.Magic */
pre.pygments .tok-vc { color: #bb60d5 } /* Name.Variable.Class */
pre.pygments .tok-vg { color: #bb60d5 } /* Name.Variable.Global */
pre.pygments .tok-vi { color: #bb60d5 } /* Name.Variable.Instance */
pre.pygments .tok-vm { color: #bb60d5 } /* Name.Variable.Magic */
pre.pygments .tok-il { color: #40a070 } /* Literal.Number.Integer.Long */
</style>
</head>
<body class="article toc2 toc-left">
<div id="buy_the_book" style="position: absolute; top: 0; right: 0; z-index:100">
<a href="/#buy_the_book">
<img src="/images/buy_the_book.svg" alt="buy the book ribbon">
</a>
</div>
<div id="header">
<div id="toc" class="toc2">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="/book/preface.html">Preface</a></li>
<li><a href="/book/introduction.html">Introduction</a></li>
<li><a href="/book/part1.html">Part 1: Building an Architecture to Support Domain Modeling</a></li>
<li><a href="/book/chapter_01_domain_model.html">1. Domain Modeling</a></li>
<li><a href="/book/chapter_02_repository.html">2. Repository Pattern</a></li>
<li><a href="/book/chapter_03_abstractions.html">3. A Brief Interlude: On Coupling <span class="keep-together">and Abstractions</span></a></li>
<li><a href="/book/chapter_04_service_layer.html">4. Our First Use Case: <span class="keep-together">Flask API and Service Layer</span></a></li>
<li><a href="/book/chapter_05_high_gear_low_gear.html">5. TDD in High Gear and Low Gear</a></li>
<li><a href="/book/chapter_06_uow.html">6. Unit of Work Pattern</a></li>
<li><a href="/book/chapter_07_aggregate.html">7. Aggregates and Consistency Boundaries</a></li>
<li><a href="/book/part2.html">Part 2: Event-Driven Architecture</a></li>
<li><a href="/book/chapter_08_events_and_message_bus.html">8. Events and the Message Bus</a></li>
<li><a href="/book/chapter_09_all_messagebus.html">9. Going to Town on the Message Bus</a></li>
<li><a href="/book/chapter_10_commands.html">10. Commands and Command Handler</a></li>
<li><a href="/book/chapter_11_external_events.html">11. Event-Driven Architecture: Using Events to Integrate Microservices</a></li>
<li><a href="/book/chapter_12_cqrs.html">12. Command-Query Responsibility Segregation (CQRS)</a></li>
<li><a href="/book/chapter_13_dependency_injection.html">13. Dependency Injection (and Bootstrapping)</a></li>
<li><a href="/book/epilogue_1_how_to_get_there_from_here.html">Epilogue: Epilogue</a></li>
<li><a href="/book/appendix_ds1_table.html">Appendix A: Summary Diagram and Table</a></li>
<li><a href="/book/appendix_project_structure.html">Appendix B: A Template Project Structure</a></li>
<li><a href="/book/appendix_csvs.html">Appendix C: Swapping Out the Infrastructure: Do Everything with CSVs</a></li>
<li><a href="/book/appendix_django.html">Appendix D: Repository and Unit of Work Patterns with Django</a></li>
<li><a href="/book/appendix_validation.html">Appendix E: Validation</a></li>
</ul>
</div>
</div>
<div id="content">
<div class="sect1">
<h2 id="chapter_05_high_gear_low_gear">5: TDD in High Gear and Low Gear<a class="anchor" href="#chapter_05_high_gear_low_gear"></a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>
We’ve introduced the service layer to capture some of the additional
orchestration responsibilities we need from a working application. The service layer helps us
clearly define our use cases and the workflow for each: what
we need to get from our repositories, what pre-checks and current state
validation we should do, and what we save at the end.</p>
</div>
<div class="paragraph">
<p>
But currently, many of our unit tests operate at a lower level, acting
directly on the model. In this chapter we’ll discuss the trade-offs
involved in moving those tests up to the service-layer level, and
some more general testing guidelines.</p>
</div>
<div class="sidebarblock">
<div class="content">
<div class="title">Harry Says: Seeing a Test Pyramid in Action Was a Light-Bulb Moment</div>
<div class="paragraph">
<p>
Here are a few words from Harry directly:</p>
</div>
<div class="paragraph">
<p><em>I was initially skeptical of all Bob’s architectural patterns, but seeing
an actual test pyramid made me a convert.</em></p>
</div>
<div class="paragraph">
<p><em>Once you implement domain modeling and the service layer, you really actually can
get to a stage where unit tests outnumber integration and end-to-end tests by
an order of magnitude. Having worked in places where the E2E test build would
take hours ("wait 'til tomorrow," essentially), I can’t tell you what a
difference it makes to be able to run all your tests in minutes or seconds.</em></p>
</div>
<div class="paragraph">
<p><em>Read on for some guidelines on how to decide what kinds of tests to write
and at which level. The high gear versus low gear way of thinking really changed
my testing life.</em></p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_how_is_our_test_pyramid_looking"><a class="anchor" href="#_how_is_our_test_pyramid_looking"></a>How Is Our Test Pyramid Looking?</h3>
<div class="paragraph">
<p>
Let’s see what this move to using a service layer, with its own service-layer tests,
does to our test pyramid:</p>
</div>
<div id="test_pyramid" class="exampleblock">
<div class="title">Counting types of tests</div>
<div class="content">
<div class="listingblock skip">
<div class="content">
<pre class="pygments highlight"><code data-lang="sh"><span></span>$<span class="tok-w"> </span>grep<span class="tok-w"> </span>-c<span class="tok-w"> </span>test_<span class="tok-w"> </span>*/*/test_*.py
tests/unit/test_allocate.py:4
tests/unit/test_batches.py:8
tests/unit/test_services.py:3
tests/integration/test_orm.py:6
tests/integration/test_repository.py:2
tests/e2e/test_api.py:2</code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>Not bad! We have 15 unit tests, 8 integration tests, and just 2 end-to-end tests. That’s
already a healthy-looking test pyramid.</p>
</div>
</div>
<div class="sect2">
<h3 id="_should_domain_layer_tests_move_to_the_service_layer"><a class="anchor" href="#_should_domain_layer_tests_move_to_the_service_layer"></a>Should Domain Layer Tests Move to the Service Layer?</h3>
<div class="paragraph">
<p>
Let’s see what happens if we take this a step further. Since we can test our
software against the service layer, we don’t really need tests for the domain
model anymore. Instead, we could rewrite all of the domain-level tests from
<a href="/book/chapter_01_domain_model.html">[chapter_01_domain_model]</a> in terms of the service layer:</p>
</div>
<div class="exampleblock">
<div class="title">Rewriting a domain test at the service layer (tests/unit/test_services.py)</div>
<div class="content">
<div class="listingblock skip">
<div class="content">
<pre class="pygments highlight"><code data-lang="python"><span></span><span class="tok-c1"># domain-layer test:</span>
<span class="tok-k">def</span> <span class="tok-nf">test_prefers_current_stock_batches_to_shipments</span><span class="tok-p">():</span>
<span class="tok-n">in_stock_batch</span> <span class="tok-o">=</span> <span class="tok-n">Batch</span><span class="tok-p">(</span><span class="tok-s2">"in-stock-batch"</span><span class="tok-p">,</span> <span class="tok-s2">"RETRO-CLOCK"</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-n">eta</span><span class="tok-o">=</span><span class="tok-kc">None</span><span class="tok-p">)</span>
<span class="tok-n">shipment_batch</span> <span class="tok-o">=</span> <span class="tok-n">Batch</span><span class="tok-p">(</span><span class="tok-s2">"shipment-batch"</span><span class="tok-p">,</span> <span class="tok-s2">"RETRO-CLOCK"</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-n">eta</span><span class="tok-o">=</span><span class="tok-n">tomorrow</span><span class="tok-p">)</span>
<span class="tok-n">line</span> <span class="tok-o">=</span> <span class="tok-n">OrderLine</span><span class="tok-p">(</span><span class="tok-s2">"oref"</span><span class="tok-p">,</span> <span class="tok-s2">"RETRO-CLOCK"</span><span class="tok-p">,</span> <span class="tok-mi">10</span><span class="tok-p">)</span>
<span class="tok-n">allocate</span><span class="tok-p">(</span><span class="tok-n">line</span><span class="tok-p">,</span> <span class="tok-p">[</span><span class="tok-n">in_stock_batch</span><span class="tok-p">,</span> <span class="tok-n">shipment_batch</span><span class="tok-p">])</span>
<span class="tok-k">assert</span> <span class="tok-n">in_stock_batch</span><span class="tok-o">.</span><span class="tok-n">available_quantity</span> <span class="tok-o">==</span> <span class="tok-mi">90</span>
<span class="tok-k">assert</span> <span class="tok-n">shipment_batch</span><span class="tok-o">.</span><span class="tok-n">available_quantity</span> <span class="tok-o">==</span> <span class="tok-mi">100</span>
<span class="tok-c1"># service-layer test:</span>
<span class="tok-k">def</span> <span class="tok-nf">test_prefers_warehouse_batches_to_shipments</span><span class="tok-p">():</span>
<span class="tok-n">in_stock_batch</span> <span class="tok-o">=</span> <span class="tok-n">Batch</span><span class="tok-p">(</span><span class="tok-s2">"in-stock-batch"</span><span class="tok-p">,</span> <span class="tok-s2">"RETRO-CLOCK"</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-n">eta</span><span class="tok-o">=</span><span class="tok-kc">None</span><span class="tok-p">)</span>
<span class="tok-n">shipment_batch</span> <span class="tok-o">=</span> <span class="tok-n">Batch</span><span class="tok-p">(</span><span class="tok-s2">"shipment-batch"</span><span class="tok-p">,</span> <span class="tok-s2">"RETRO-CLOCK"</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-n">eta</span><span class="tok-o">=</span><span class="tok-n">tomorrow</span><span class="tok-p">)</span>
<span class="tok-n">repo</span> <span class="tok-o">=</span> <span class="tok-n">FakeRepository</span><span class="tok-p">([</span><span class="tok-n">in_stock_batch</span><span class="tok-p">,</span> <span class="tok-n">shipment_batch</span><span class="tok-p">])</span>
<span class="tok-n">session</span> <span class="tok-o">=</span> <span class="tok-n">FakeSession</span><span class="tok-p">()</span>
<span class="tok-n">line</span> <span class="tok-o">=</span> <span class="tok-n">OrderLine</span><span class="tok-p">(</span><span class="tok-s1">'oref'</span><span class="tok-p">,</span> <span class="tok-s2">"RETRO-CLOCK"</span><span class="tok-p">,</span> <span class="tok-mi">10</span><span class="tok-p">)</span>
<span class="tok-n">services</span><span class="tok-o">.</span><span class="tok-n">allocate</span><span class="tok-p">(</span><span class="tok-n">line</span><span class="tok-p">,</span> <span class="tok-n">repo</span><span class="tok-p">,</span> <span class="tok-n">session</span><span class="tok-p">)</span>
<span class="tok-k">assert</span> <span class="tok-n">in_stock_batch</span><span class="tok-o">.</span><span class="tok-n">available_quantity</span> <span class="tok-o">==</span> <span class="tok-mi">90</span>
<span class="tok-k">assert</span> <span class="tok-n">shipment_batch</span><span class="tok-o">.</span><span class="tok-n">available_quantity</span> <span class="tok-o">==</span> <span class="tok-mi">100</span></code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>
Why would we want to do that?</p>
</div>
<div class="paragraph">
<p>Tests are supposed to help us change our system fearlessly, but often
we see teams writing too many tests against their domain model. This causes
problems when they come to change their codebase and find that they need to
update tens or even hundreds of unit tests.</p>
</div>
<div class="paragraph">
<p>This makes sense if you stop to think about the purpose of automated tests. We
use tests to enforce that a property of the system doesn’t change while we’re
working. We use tests to check that the API continues to return 200, that the
database session continues to commit, and that orders are still being allocated.</p>
</div>
<div class="paragraph">
<p>If we accidentally change one of those behaviors, our tests will break. The
flip side, though, is that if we want to change the design of our code, any
tests relying directly on that code will also fail.</p>
</div>
<div class="paragraph">
<p>As we get further into the book, you’ll see how the service layer forms an API
for our system that we can drive in multiple ways. Testing against this API
reduces the amount of code that we need to change when we refactor our domain
model. If we restrict ourselves to testing only against the service layer,
we won’t have any tests that directly interact with "private" methods or
attributes on our model objects, which leaves us freer to refactor them.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
Every line of code that we put in a test is like a blob of glue, holding
the system in a particular shape. The more low-level tests we have, the
harder it will be to change things.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="kinds_of_tests"><a class="anchor" href="#kinds_of_tests"></a>On Deciding What Kind of Tests to Write</h3>
<div class="paragraph">
<p>
You might be asking yourself, "Should I rewrite all my unit tests, then? Is it
wrong to write tests against the domain model?" To answer those questions, it’s
important to understand the trade-off between coupling and design feedback (see
<a href="#test_spectrum_diagram">The test spectrum</a>).</p>
</div>
<div id="test_spectrum_diagram" class="imageblock">
<div class="content">
<img src="images/apwp_0501.png" alt="apwp 0501">
</div>
<div class="title">Figure 1. The test spectrum</div>
</div>
<div class="listingblock image-source">
<div class="content">
<pre>[ditaa, apwp_0501]
| Low feedback High feedback |
| Low barrier to change High barrier to change |
| High system coverage Focused coverage |
| |
| <--------- ----------> |
| |
| API Tests Service–Layer Tests Domain Tests |</pre>
</div>
</div>
<div class="paragraph">
<p>
Extreme programming (XP) exhorts us to "listen to the code." When we’re writing
tests, we might find that the code is hard to use or notice a code smell. This
is a trigger for us to refactor, and to reconsider our design.</p>
</div>
<div class="paragraph">
<p>We only get that feedback, though, when we’re working closely with the target
code. A test for the HTTP API tells us nothing about the fine-grained design of
our objects, because it sits at a much higher level of abstraction.</p>
</div>
<div class="paragraph">
<p>On the other hand, we can rewrite our entire application and, so long as we
don’t change the URLs or request formats, our HTTP tests will continue to pass.
This gives us confidence that large-scale changes, like changing the database schema,
haven’t broken our code.</p>
</div>
<div class="paragraph">
<p>At the other end of the spectrum, the tests we wrote in <a href="/book/chapter_01_domain_model.html">[chapter_01_domain_model]</a> helped us to
flesh out our understanding of the objects we need. The tests guided us to a
design that makes sense and reads in the domain language. When our tests read
in the domain language, we feel comfortable that our code matches our intuition
about the problem we’re trying to solve.</p>
</div>
<div class="paragraph">
<p>Because the tests are written in the domain language, they act as living
documentation for our model. A new team member can read these tests to quickly
understand how the system works and how the core concepts interrelate.</p>
</div>
<div class="paragraph">
<p>We often "sketch" new behaviors by writing tests at this level to see how the
code might look. When we want to improve the design of the code, though, we will need to replace
or delete these tests, because they are tightly coupled to a particular
<span class="keep-together">implementation</span>.</p>
</div>
</div>
<div class="sect2">
<h3 id="_high_and_low_gear"><a class="anchor" href="#_high_and_low_gear"></a>High and Low Gear</h3>
<div class="paragraph">
<p>
Most of the time, when we are adding a new feature or fixing a bug, we don’t
need to make extensive changes to the domain model. In these cases, we prefer
to write tests against services because of the lower coupling and higher coverage.</p>
</div>
<div class="paragraph">
<p>
For example, when writing an <code>add_stock</code> function or a <code>cancel_order</code> feature,
we can work more quickly and with less coupling by writing tests against the
service layer.</p>
</div>
<div class="paragraph">
<p>
When starting a new project or when hitting a particularly gnarly problem,
we will drop back down to writing tests against the domain model so we
get better feedback and executable documentation of our intent.</p>
</div>
<div class="paragraph">
<p>The metaphor we use is that of shifting gears. When starting a journey, the
bicycle needs to be in a low gear so that it can overcome inertia. Once we’re off
and running, we can go faster and more efficiently by changing into a high gear;
but if we suddenly encounter a steep hill or are forced to slow down by a
hazard, we again drop down to a low gear until we can pick up speed again.</p>
</div>
</div>
<div class="sect2">
<h3 id="primitive_obsession"><a class="anchor" href="#primitive_obsession"></a>Fully Decoupling the Service-Layer Tests from the Domain</h3>
<div class="paragraph">
<p>
We still have direct dependencies on the domain in our service-layer
tests, because we use domain objects to set up our test data and to invoke
our service-layer functions.</p>
</div>
<div class="paragraph">
<p>To have a service layer that’s fully decoupled from the domain, we need to
rewrite its API to work in terms of primitives.</p>
</div>
<div class="paragraph">
<p>Our service layer currently takes an <code>OrderLine</code> domain object:</p>
</div>
<div id="service_domain" class="exampleblock">
<div class="title">Before: allocate takes a domain object (service_layer/services.py)</div>
<div class="content">
<div class="listingblock skip">
<div class="content">
<pre class="pygments highlight"><code data-lang="python"><span></span><span class="tok-k">def</span> <span class="tok-nf">allocate</span><span class="tok-p">(</span><span class="tok-n">line</span><span class="tok-p">:</span> <span class="tok-n">OrderLine</span><span class="tok-p">,</span> <span class="tok-n">repo</span><span class="tok-p">:</span> <span class="tok-n">AbstractRepository</span><span class="tok-p">,</span> <span class="tok-n">session</span><span class="tok-p">)</span> <span class="tok-o">-></span> <span class="tok-nb">str</span><span class="tok-p">:</span></code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>How would it look if its parameters were all primitive types?</p>
</div>
<div id="service_takes_primitives" class="exampleblock">
<div class="title">After: allocate takes strings and ints (service_layer/services.py)</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="python"><span></span><span class="tok-k">def</span> <span class="tok-nf">allocate</span><span class="tok-p">(</span>
<span class="tok-n">orderid</span><span class="tok-p">:</span> <span class="tok-nb">str</span><span class="tok-p">,</span> <span class="tok-n">sku</span><span class="tok-p">:</span> <span class="tok-nb">str</span><span class="tok-p">,</span> <span class="tok-n">qty</span><span class="tok-p">:</span> <span class="tok-nb">int</span><span class="tok-p">,</span>
<span class="tok-n">repo</span><span class="tok-p">:</span> <span class="tok-n">AbstractRepository</span><span class="tok-p">,</span> <span class="tok-n">session</span>
<span class="tok-p">)</span> <span class="tok-o">-></span> <span class="tok-nb">str</span><span class="tok-p">:</span></code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>We rewrite the tests in those terms as well:</p>
</div>
<div id="tests_call_with_primitives" class="exampleblock">
<div class="title">Tests now use primitives in function call (tests/unit/test_services.py)</div>
<div class="content">
<div class="listingblock non-head">
<div class="content">
<pre class="pygments highlight"><code data-lang="python"><span></span><span class="tok-k">def</span> <span class="tok-nf">test_returns_allocation</span><span class="tok-p">():</span>
<span class="tok-n">batch</span> <span class="tok-o">=</span> <span class="tok-n">model</span><span class="tok-o">.</span><span class="tok-n">Batch</span><span class="tok-p">(</span><span class="tok-s2">"batch1"</span><span class="tok-p">,</span> <span class="tok-s2">"COMPLICATED-LAMP"</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-n">eta</span><span class="tok-o">=</span><span class="tok-kc">None</span><span class="tok-p">)</span>
<span class="tok-n">repo</span> <span class="tok-o">=</span> <span class="tok-n">FakeRepository</span><span class="tok-p">([</span><span class="tok-n">batch</span><span class="tok-p">])</span>
<span class="tok-n">result</span> <span class="tok-o">=</span> <span class="tok-n">services</span><span class="tok-o">.</span><span class="tok-n">allocate</span><span class="tok-p">(</span><span class="tok-s2">"o1"</span><span class="tok-p">,</span> <span class="tok-s2">"COMPLICATED-LAMP"</span><span class="tok-p">,</span> <span class="tok-mi">10</span><span class="tok-p">,</span> <span class="tok-n">repo</span><span class="tok-p">,</span> <span class="tok-n">FakeSession</span><span class="tok-p">())</span>
<span class="tok-k">assert</span> <span class="tok-n">result</span> <span class="tok-o">==</span> <span class="tok-s2">"batch1"</span></code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>But our tests still depend on the domain, because we still manually instantiate
<code>Batch</code> objects. So, if one day we decide to massively refactor how our <code>Batch</code>
model works, we’ll have to change a bunch of tests.</p>
</div>
<div class="sect3">
<h4 id="_mitigation_keep_all_domain_dependencies_in_fixture_functions"><a class="anchor" href="#_mitigation_keep_all_domain_dependencies_in_fixture_functions"></a>Mitigation: Keep All Domain Dependencies in Fixture Functions</h4>
<div class="paragraph">
<p>
We could at least abstract that out to a helper function or a fixture
in our tests. Here’s one way you could do that, adding a factory
function on <code>FakeRepository</code>:</p>
</div>
<div id="services_factory_function" class="exampleblock">
<div class="title">Factory functions for fixtures are one possibility (tests/unit/test_services.py)</div>
<div class="content">
<div class="listingblock skip">
<div class="content">
<pre class="pygments highlight"><code data-lang="python"><span></span><span class="tok-k">class</span> <span class="tok-nc">FakeRepository</span><span class="tok-p">(</span><span class="tok-nb">set</span><span class="tok-p">):</span>
<span class="tok-nd">@staticmethod</span>
<span class="tok-k">def</span> <span class="tok-nf">for_batch</span><span class="tok-p">(</span><span class="tok-n">ref</span><span class="tok-p">,</span> <span class="tok-n">sku</span><span class="tok-p">,</span> <span class="tok-n">qty</span><span class="tok-p">,</span> <span class="tok-n">eta</span><span class="tok-o">=</span><span class="tok-kc">None</span><span class="tok-p">):</span>
<span class="tok-k">return</span> <span class="tok-n">FakeRepository</span><span class="tok-p">([</span>
<span class="tok-n">model</span><span class="tok-o">.</span><span class="tok-n">Batch</span><span class="tok-p">(</span><span class="tok-n">ref</span><span class="tok-p">,</span> <span class="tok-n">sku</span><span class="tok-p">,</span> <span class="tok-n">qty</span><span class="tok-p">,</span> <span class="tok-n">eta</span><span class="tok-p">),</span>
<span class="tok-p">])</span>
<span class="tok-o">...</span>
<span class="tok-k">def</span> <span class="tok-nf">test_returns_allocation</span><span class="tok-p">():</span>
<span class="tok-n">repo</span> <span class="tok-o">=</span> <span class="tok-n">FakeRepository</span><span class="tok-o">.</span><span class="tok-n">for_batch</span><span class="tok-p">(</span><span class="tok-s2">"batch1"</span><span class="tok-p">,</span> <span class="tok-s2">"COMPLICATED-LAMP"</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-n">eta</span><span class="tok-o">=</span><span class="tok-kc">None</span><span class="tok-p">)</span>
<span class="tok-n">result</span> <span class="tok-o">=</span> <span class="tok-n">services</span><span class="tok-o">.</span><span class="tok-n">allocate</span><span class="tok-p">(</span><span class="tok-s2">"o1"</span><span class="tok-p">,</span> <span class="tok-s2">"COMPLICATED-LAMP"</span><span class="tok-p">,</span> <span class="tok-mi">10</span><span class="tok-p">,</span> <span class="tok-n">repo</span><span class="tok-p">,</span> <span class="tok-n">FakeSession</span><span class="tok-p">())</span>
<span class="tok-k">assert</span> <span class="tok-n">result</span> <span class="tok-o">==</span> <span class="tok-s2">"batch1"</span></code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>At least that would move all of our tests' dependencies on the domain
into one place.</p>
</div>
</div>
<div class="sect3">
<h4 id="_adding_a_missing_service"><a class="anchor" href="#_adding_a_missing_service"></a>Adding a Missing Service</h4>
<div class="paragraph">
<p>
We could go one step further, though. If we had a service to add stock,
we could use that and make our service-layer tests fully expressed
in terms of the service layer’s official use cases, removing all dependencies
on the domain:</p>
</div>
<div id="test_add_batch" class="exampleblock">
<div class="title">Test for new add_batch service (tests/unit/test_services.py)</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="python"><span></span><span class="tok-k">def</span> <span class="tok-nf">test_add_batch</span><span class="tok-p">():</span>
<span class="tok-n">repo</span><span class="tok-p">,</span> <span class="tok-n">session</span> <span class="tok-o">=</span> <span class="tok-n">FakeRepository</span><span class="tok-p">([]),</span> <span class="tok-n">FakeSession</span><span class="tok-p">()</span>
<span class="tok-n">services</span><span class="tok-o">.</span><span class="tok-n">add_batch</span><span class="tok-p">(</span><span class="tok-s2">"b1"</span><span class="tok-p">,</span> <span class="tok-s2">"CRUNCHY-ARMCHAIR"</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-kc">None</span><span class="tok-p">,</span> <span class="tok-n">repo</span><span class="tok-p">,</span> <span class="tok-n">session</span><span class="tok-p">)</span>
<span class="tok-k">assert</span> <span class="tok-n">repo</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-p">(</span><span class="tok-s2">"b1"</span><span class="tok-p">)</span> <span class="tok-ow">is</span> <span class="tok-ow">not</span> <span class="tok-kc">None</span>
<span class="tok-k">assert</span> <span class="tok-n">session</span><span class="tok-o">.</span><span class="tok-n">committed</span></code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
In general, if you find yourself needing to do domain-layer stuff directly
in your service-layer tests, it may be an indication that your service
layer is incomplete.
</td>
</tr>
</table>
</div>
<div class="paragraph pagebreak-before">
<p>And the implementation is just two lines:</p>
</div>
<div id="add_batch_service" class="exampleblock">
<div class="title">A new service for add_batch (service_layer/services.py)</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="python"><span></span><span class="tok-k">def</span> <span class="tok-nf">add_batch</span><span class="tok-p">(</span>
<span class="tok-n">ref</span><span class="tok-p">:</span> <span class="tok-nb">str</span><span class="tok-p">,</span> <span class="tok-n">sku</span><span class="tok-p">:</span> <span class="tok-nb">str</span><span class="tok-p">,</span> <span class="tok-n">qty</span><span class="tok-p">:</span> <span class="tok-nb">int</span><span class="tok-p">,</span> <span class="tok-n">eta</span><span class="tok-p">:</span> <span class="tok-n">Optional</span><span class="tok-p">[</span><span class="tok-n">date</span><span class="tok-p">],</span>
<span class="tok-n">repo</span><span class="tok-p">:</span> <span class="tok-n">AbstractRepository</span><span class="tok-p">,</span> <span class="tok-n">session</span><span class="tok-p">,</span>
<span class="tok-p">)</span> <span class="tok-o">-></span> <span class="tok-kc">None</span><span class="tok-p">:</span>
<span class="tok-n">repo</span><span class="tok-o">.</span><span class="tok-n">add</span><span class="tok-p">(</span><span class="tok-n">model</span><span class="tok-o">.</span><span class="tok-n">Batch</span><span class="tok-p">(</span><span class="tok-n">ref</span><span class="tok-p">,</span> <span class="tok-n">sku</span><span class="tok-p">,</span> <span class="tok-n">qty</span><span class="tok-p">,</span> <span class="tok-n">eta</span><span class="tok-p">))</span>
<span class="tok-n">session</span><span class="tok-o">.</span><span class="tok-n">commit</span><span class="tok-p">()</span>
<span class="tok-k">def</span> <span class="tok-nf">allocate</span><span class="tok-p">(</span>
<span class="tok-n">orderid</span><span class="tok-p">:</span> <span class="tok-nb">str</span><span class="tok-p">,</span> <span class="tok-n">sku</span><span class="tok-p">:</span> <span class="tok-nb">str</span><span class="tok-p">,</span> <span class="tok-n">qty</span><span class="tok-p">:</span> <span class="tok-nb">int</span><span class="tok-p">,</span>
<span class="tok-n">repo</span><span class="tok-p">:</span> <span class="tok-n">AbstractRepository</span><span class="tok-p">,</span> <span class="tok-n">session</span>
<span class="tok-p">)</span> <span class="tok-o">-></span> <span class="tok-nb">str</span><span class="tok-p">:</span></code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
Should you write a new service just because it would help remove
dependencies from your tests? Probably not. But in this case, we
almost definitely would need an <code>add_batch</code> service one day <span class="keep-together">anyway</span>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>
That now allows us to rewrite <em>all</em> of our service-layer tests purely
in terms of the services themselves, using only primitives, and without
any dependencies on the model:</p>
</div>
<div id="services_tests_all_services" class="exampleblock">
<div class="title">Services tests now use only services (tests/unit/test_services.py)</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="python"><span></span><span class="tok-k">def</span> <span class="tok-nf">test_allocate_returns_allocation</span><span class="tok-p">():</span>
<span class="tok-n">repo</span><span class="tok-p">,</span> <span class="tok-n">session</span> <span class="tok-o">=</span> <span class="tok-n">FakeRepository</span><span class="tok-p">([]),</span> <span class="tok-n">FakeSession</span><span class="tok-p">()</span>
<span class="tok-n">services</span><span class="tok-o">.</span><span class="tok-n">add_batch</span><span class="tok-p">(</span><span class="tok-s2">"batch1"</span><span class="tok-p">,</span> <span class="tok-s2">"COMPLICATED-LAMP"</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-kc">None</span><span class="tok-p">,</span> <span class="tok-n">repo</span><span class="tok-p">,</span> <span class="tok-n">session</span><span class="tok-p">)</span>
<span class="tok-n">result</span> <span class="tok-o">=</span> <span class="tok-n">services</span><span class="tok-o">.</span><span class="tok-n">allocate</span><span class="tok-p">(</span><span class="tok-s2">"o1"</span><span class="tok-p">,</span> <span class="tok-s2">"COMPLICATED-LAMP"</span><span class="tok-p">,</span> <span class="tok-mi">10</span><span class="tok-p">,</span> <span class="tok-n">repo</span><span class="tok-p">,</span> <span class="tok-n">session</span><span class="tok-p">)</span>
<span class="tok-k">assert</span> <span class="tok-n">result</span> <span class="tok-o">==</span> <span class="tok-s2">"batch1"</span>
<span class="tok-k">def</span> <span class="tok-nf">test_allocate_errors_for_invalid_sku</span><span class="tok-p">():</span>
<span class="tok-n">repo</span><span class="tok-p">,</span> <span class="tok-n">session</span> <span class="tok-o">=</span> <span class="tok-n">FakeRepository</span><span class="tok-p">([]),</span> <span class="tok-n">FakeSession</span><span class="tok-p">()</span>
<span class="tok-n">services</span><span class="tok-o">.</span><span class="tok-n">add_batch</span><span class="tok-p">(</span><span class="tok-s2">"b1"</span><span class="tok-p">,</span> <span class="tok-s2">"AREALSKU"</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-kc">None</span><span class="tok-p">,</span> <span class="tok-n">repo</span><span class="tok-p">,</span> <span class="tok-n">session</span><span class="tok-p">)</span>
<span class="tok-k">with</span> <span class="tok-n">pytest</span><span class="tok-o">.</span><span class="tok-n">raises</span><span class="tok-p">(</span><span class="tok-n">services</span><span class="tok-o">.</span><span class="tok-n">InvalidSku</span><span class="tok-p">,</span> <span class="tok-n">match</span><span class="tok-o">=</span><span class="tok-s2">"Invalid sku NONEXISTENTSKU"</span><span class="tok-p">):</span>
<span class="tok-n">services</span><span class="tok-o">.</span><span class="tok-n">allocate</span><span class="tok-p">(</span><span class="tok-s2">"o1"</span><span class="tok-p">,</span> <span class="tok-s2">"NONEXISTENTSKU"</span><span class="tok-p">,</span> <span class="tok-mi">10</span><span class="tok-p">,</span> <span class="tok-n">repo</span><span class="tok-p">,</span> <span class="tok-n">FakeSession</span><span class="tok-p">())</span></code></pre>
</div>
</div>
</div>
</div>
<div class="paragraph">
<p>
This is a really nice place to be in. Our service-layer tests depend on only
the service layer itself, leaving us completely free to refactor the model as
we see fit.</p>
</div>
</div>
</div>
<div class="sect2 pagebreak-before less_space">
<h3 id="_carrying_the_improvement_through_to_the_e2e_tests"><a class="anchor" href="#_carrying_the_improvement_through_to_the_e2e_tests"></a>Carrying the Improvement Through to the E2E Tests</h3>
<div class="paragraph">
<p>
In the same way that adding <code>add_batch</code> helped decouple our service-layer
tests from the model, adding an API endpoint to add a batch would remove
the need for the ugly <code>add_stock</code> fixture, and our E2E tests could be free
of those hardcoded SQL queries and the direct dependency on the database.</p>
</div>
<div class="paragraph">
<p>Thanks to our service function, adding the endpoint is easy, with just a little
JSON wrangling and a single function call required:</p>
</div>
<div id="api_for_add_batch" class="exampleblock">
<div class="title">API for adding a batch (entrypoints/flask_app.py)</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="python"><span></span><span class="tok-nd">@app</span><span class="tok-o">.</span><span class="tok-n">route</span><span class="tok-p">(</span><span class="tok-s2">"/add_batch"</span><span class="tok-p">,</span> <span class="tok-n">methods</span><span class="tok-o">=</span><span class="tok-p">[</span><span class="tok-s2">"POST"</span><span class="tok-p">])</span>
<span class="tok-k">def</span> <span class="tok-nf">add_batch</span><span class="tok-p">():</span>
<span class="tok-n">session</span> <span class="tok-o">=</span> <span class="tok-n">get_session</span><span class="tok-p">()</span>
<span class="tok-n">repo</span> <span class="tok-o">=</span> <span class="tok-n">repository</span><span class="tok-o">.</span><span class="tok-n">SqlAlchemyRepository</span><span class="tok-p">(</span><span class="tok-n">session</span><span class="tok-p">)</span>
<span class="tok-n">eta</span> <span class="tok-o">=</span> <span class="tok-n">request</span><span class="tok-o">.</span><span class="tok-n">json</span><span class="tok-p">[</span><span class="tok-s2">"eta"</span><span class="tok-p">]</span>
<span class="tok-k">if</span> <span class="tok-n">eta</span> <span class="tok-ow">is</span> <span class="tok-ow">not</span> <span class="tok-kc">None</span><span class="tok-p">:</span>
<span class="tok-n">eta</span> <span class="tok-o">=</span> <span class="tok-n">datetime</span><span class="tok-o">.</span><span class="tok-n">fromisoformat</span><span class="tok-p">(</span><span class="tok-n">eta</span><span class="tok-p">)</span><span class="tok-o">.</span><span class="tok-n">date</span><span class="tok-p">()</span>
<span class="tok-n">services</span><span class="tok-o">.</span><span class="tok-n">add_batch</span><span class="tok-p">(</span>
<span class="tok-n">request</span><span class="tok-o">.</span><span class="tok-n">json</span><span class="tok-p">[</span><span class="tok-s2">"ref"</span><span class="tok-p">],</span>
<span class="tok-n">request</span><span class="tok-o">.</span><span class="tok-n">json</span><span class="tok-p">[</span><span class="tok-s2">"sku"</span><span class="tok-p">],</span>
<span class="tok-n">request</span><span class="tok-o">.</span><span class="tok-n">json</span><span class="tok-p">[</span><span class="tok-s2">"qty"</span><span class="tok-p">],</span>
<span class="tok-n">eta</span><span class="tok-p">,</span>
<span class="tok-n">repo</span><span class="tok-p">,</span>
<span class="tok-n">session</span><span class="tok-p">,</span>
<span class="tok-p">)</span>
<span class="tok-k">return</span> <span class="tok-s2">"OK"</span><span class="tok-p">,</span> <span class="tok-mi">201</span></code></pre>
</div>
</div>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
Are you thinking to yourself, POST to <em>/add_batch</em>? That’s not
very RESTful! You’re quite right. We’re being happily sloppy, but
if you’d like to make it all more RESTy, maybe a POST to <em>/batches</em>,
then knock yourself out! Because Flask is a thin adapter, it’ll be
easy. See <a href="#types_of_test_rules_of_thumb">the next sidebar</a>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>And our hardcoded SQL queries from <em>conftest.py</em> get replaced with some
API calls, meaning the API tests have no dependencies other than the API,
which is also nice:</p>
</div>
<div id="api_tests_with_no_sql" class="exampleblock">
<div class="title">API tests can now add their own batches (tests/e2e/test_api.py)</div>
<div class="content">
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="python"><span></span><span class="tok-k">def</span> <span class="tok-nf">post_to_add_batch</span><span class="tok-p">(</span><span class="tok-n">ref</span><span class="tok-p">,</span> <span class="tok-n">sku</span><span class="tok-p">,</span> <span class="tok-n">qty</span><span class="tok-p">,</span> <span class="tok-n">eta</span><span class="tok-p">):</span>
<span class="tok-n">url</span> <span class="tok-o">=</span> <span class="tok-n">config</span><span class="tok-o">.</span><span class="tok-n">get_api_url</span><span class="tok-p">()</span>
<span class="tok-n">r</span> <span class="tok-o">=</span> <span class="tok-n">requests</span><span class="tok-o">.</span><span class="tok-n">post</span><span class="tok-p">(</span>
<span class="tok-sa">f</span><span class="tok-s2">"</span><span class="tok-si">{</span><span class="tok-n">url</span><span class="tok-si">}</span><span class="tok-s2">/add_batch"</span><span class="tok-p">,</span> <span class="tok-n">json</span><span class="tok-o">=</span><span class="tok-p">{</span><span class="tok-s2">"ref"</span><span class="tok-p">:</span> <span class="tok-n">ref</span><span class="tok-p">,</span> <span class="tok-s2">"sku"</span><span class="tok-p">:</span> <span class="tok-n">sku</span><span class="tok-p">,</span> <span class="tok-s2">"qty"</span><span class="tok-p">:</span> <span class="tok-n">qty</span><span class="tok-p">,</span> <span class="tok-s2">"eta"</span><span class="tok-p">:</span> <span class="tok-n">eta</span><span class="tok-p">}</span>
<span class="tok-p">)</span>
<span class="tok-k">assert</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">status_code</span> <span class="tok-o">==</span> <span class="tok-mi">201</span>
<span class="tok-nd">@pytest</span><span class="tok-o">.</span><span class="tok-n">mark</span><span class="tok-o">.</span><span class="tok-n">usefixtures</span><span class="tok-p">(</span><span class="tok-s2">"postgres_db"</span><span class="tok-p">)</span>
<span class="tok-nd">@pytest</span><span class="tok-o">.</span><span class="tok-n">mark</span><span class="tok-o">.</span><span class="tok-n">usefixtures</span><span class="tok-p">(</span><span class="tok-s2">"restart_api"</span><span class="tok-p">)</span>
<span class="tok-k">def</span> <span class="tok-nf">test_happy_path_returns_201_and_allocated_batch</span><span class="tok-p">():</span>
<span class="tok-n">sku</span><span class="tok-p">,</span> <span class="tok-n">othersku</span> <span class="tok-o">=</span> <span class="tok-n">random_sku</span><span class="tok-p">(),</span> <span class="tok-n">random_sku</span><span class="tok-p">(</span><span class="tok-s2">"other"</span><span class="tok-p">)</span>
<span class="tok-n">earlybatch</span> <span class="tok-o">=</span> <span class="tok-n">random_batchref</span><span class="tok-p">(</span><span class="tok-mi">1</span><span class="tok-p">)</span>
<span class="tok-n">laterbatch</span> <span class="tok-o">=</span> <span class="tok-n">random_batchref</span><span class="tok-p">(</span><span class="tok-mi">2</span><span class="tok-p">)</span>
<span class="tok-n">otherbatch</span> <span class="tok-o">=</span> <span class="tok-n">random_batchref</span><span class="tok-p">(</span><span class="tok-mi">3</span><span class="tok-p">)</span>
<span class="tok-n">post_to_add_batch</span><span class="tok-p">(</span><span class="tok-n">laterbatch</span><span class="tok-p">,</span> <span class="tok-n">sku</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-s2">"2011-01-02"</span><span class="tok-p">)</span>
<span class="tok-n">post_to_add_batch</span><span class="tok-p">(</span><span class="tok-n">earlybatch</span><span class="tok-p">,</span> <span class="tok-n">sku</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-s2">"2011-01-01"</span><span class="tok-p">)</span>
<span class="tok-n">post_to_add_batch</span><span class="tok-p">(</span><span class="tok-n">otherbatch</span><span class="tok-p">,</span> <span class="tok-n">othersku</span><span class="tok-p">,</span> <span class="tok-mi">100</span><span class="tok-p">,</span> <span class="tok-kc">None</span><span class="tok-p">)</span>
<span class="tok-n">data</span> <span class="tok-o">=</span> <span class="tok-p">{</span><span class="tok-s2">"orderid"</span><span class="tok-p">:</span> <span class="tok-n">random_orderid</span><span class="tok-p">(),</span> <span class="tok-s2">"sku"</span><span class="tok-p">:</span> <span class="tok-n">sku</span><span class="tok-p">,</span> <span class="tok-s2">"qty"</span><span class="tok-p">:</span> <span class="tok-mi">3</span><span class="tok-p">}</span>
<span class="tok-n">url</span> <span class="tok-o">=</span> <span class="tok-n">config</span><span class="tok-o">.</span><span class="tok-n">get_api_url</span><span class="tok-p">()</span>
<span class="tok-n">r</span> <span class="tok-o">=</span> <span class="tok-n">requests</span><span class="tok-o">.</span><span class="tok-n">post</span><span class="tok-p">(</span><span class="tok-sa">f</span><span class="tok-s2">"</span><span class="tok-si">{</span><span class="tok-n">url</span><span class="tok-si">}</span><span class="tok-s2">/allocate"</span><span class="tok-p">,</span> <span class="tok-n">json</span><span class="tok-o">=</span><span class="tok-n">data</span><span class="tok-p">)</span>
<span class="tok-k">assert</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">status_code</span> <span class="tok-o">==</span> <span class="tok-mi">201</span>
<span class="tok-k">assert</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">json</span><span class="tok-p">()[</span><span class="tok-s2">"batchref"</span><span class="tok-p">]</span> <span class="tok-o">==</span> <span class="tok-n">earlybatch</span></code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_wrap_up"><a class="anchor" href="#_wrap_up"></a>Wrap-Up</h3>
<div class="paragraph">
<p>
Once you have a service layer in place, you really can move the majority
of your test coverage to unit tests and develop a healthy test pyramid.</p>
</div>
<div id="types_of_test_rules_of_thumb" class="sidebarblock nobreakinside less_space">
<div class="content">
<div class="title">Recap: Rules of Thumb for Different Types of Test</div>
<div class="dlist">
<dl>
<dt class="hdlist1">Aim for one end-to-end test per feature</dt>
<dd>
<p>This might be written against an HTTP API, for example. The objective
is to demonstrate that the feature works, and that all the moving parts
are glued together correctly.
</p>
</dd>
<dt class="hdlist1">Write the bulk of your tests against the service layer</dt>
<dd>
<p>These edge-to-edge tests offer a good trade-off between coverage,
runtime, and efficiency. Each test tends to cover one code path of a
feature and use fakes for I/O. This is the place to exhaustively
cover all the edge cases and the ins and outs of your business logic.<sup class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnotedef_1" title="View footnote.">1</a>]</sup>
</p>
</dd>
<dt class="hdlist1">Maintain a small core of tests written against your domain model</dt>
<dd>
<p>These tests have highly focused coverage and are more brittle, but they have
the highest feedback. Don’t be afraid to delete these tests if the
functionality is later covered by tests at the service layer.
</p>
</dd>
<dt class="hdlist1">Error handling counts as a feature</dt>
<dd>
<p>Ideally, your application will be structured such that all errors that
bubble up to your entrypoints (e.g., Flask) are handled in the same way.
This means you need to test only the happy path for each feature, and to
reserve one end-to-end test for all unhappy paths (and many unhappy path
unit tests, of course).
</p>
</dd>
</dl>
</div>
</div>
</div>
<div class="paragraph">
<p>A few
things will help along the way:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Express your service layer in terms of primitives rather than domain objects.</p>
</li>
<li>
<p>In an ideal world, you’ll have all the services you need to be able to test
entirely against the service layer, rather than hacking state via
repositories or the database. This pays off in your end-to-end tests as well.
</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Onto the next chapter!</p>
</div>
</div>
</div>
</div>
<div class="prev_and_next_chapter_links">
<hr>
<a class="prev_chapter_link" href="/book/chapter_04_service_layer.html"><< Previous - 4: Our First Use Case: Flask API and Service Layer</a>
<a class="next_chapter_link" href="/book/chapter_06_uow.html">Next - 6: Unit of Work Pattern >></a>
</div>
</div>
<div id="footnotes">
<hr>
<div class="footnote" id="_footnotedef_1">
<a href="#_footnoteref_1">1</a>. A valid concern about writing tests at a higher level is that it can lead to combinatorial explosion for more complex use cases. In these cases, dropping down to lower-level unit tests of the various collaborating domain objects can be useful. But see also <a href="/book/chapter_08_events_and_message_bus.html">[chapter_08_events_and_message_bus]</a> and <a href="/book/chapter_09_all_messagebus.html#fake_message_bus">[fake_message_bus]</a>.
</div>
</div>
<div id="footer">
<div id="footer-text">
Last updated 2023-11-24 02:20:52 UTC
</div>
</div>
<div><div id="disqus_thread" style="margin: 10px"></div>
<script>
var disqus_config = function () {
this.page.url = 'https://www.cosmicpython.com/book/chapter_05_high_gear_low_gear.html';
this.page.identifier = 'cosmic-python-chapter_05_high_gear_low_gear';
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://cosmic-python.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div><html><head><script async src="https://www.googletagmanager.com/gtag/js?id=UA-40928035-3"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-40928035-3');
</script>
</head></html></body>
</html>