<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pedram Hajesmaeeli on Medium]]></title>
        <description><![CDATA[Stories by Pedram Hajesmaeeli on Medium]]></description>
        <link>https://medium.com/@pedram.esmaeeli?source=rss-62dc16552c97------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2wrbJDoSOwQGy1AjIzNTvw.jpeg</url>
            <title>Stories by Pedram Hajesmaeeli on Medium</title>
            <link>https://medium.com/@pedram.esmaeeli?source=rss-62dc16552c97------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:48:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pedram.esmaeeli/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Type-safe mocking in Python: A new approach with tmock]]></title>
            <link>https://medium.com/@pedram.esmaeeli/type-safe-mocking-in-python-a-new-approach-with-tmock-0e2e5d7e9114?source=rss-62dc16552c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e2e5d7e9114</guid>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Pedram Hajesmaeeli]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 14:58:03 GMT</pubDate>
            <atom:updated>2026-04-11T17:48:10.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQH3mJIBJt6VTAqbkvFkhQ.png" /></figure><p>Throughout my career, I’ve always been fascinated by mocks. After working with <strong>Mockito</strong> and <strong>Mockk</strong> in the Java ecosystem for several years, I recently returned to Python. This time, however, the standard approach to mocking looked far from intuitive.</p><p>While I enjoy the flexibility of patching things on the fly, Python’s MagicMock felt a bit <em>too</em> magical. The fact that you can use mocks without defining stubs first, is a complete departure from most modern mock libraries.</p><p>More importantly, MagicMock is incredibly lenient: it allows for the wrong number of arguments, accepts incorrect types for both arguments and return values, and, depending on how it is used, it might even allow typos in the method names.</p><p>In a modern Python ecosystem that has embraced static typing through tools like mypy and pyright this much flexibility started to feel more like a liability than a feature. It effectively bypasses your type-safety and renders your IDE’s autocomplete useless.</p><p>I wanted a library that combined the surgical behavior of unittest.mock.patch combined with the strict contract enforcement of Mockito. I wanted my mocks to tell the truth… If I refactor a method signature and forget to adjust a caller, I want my tests to break immediately. Not on production.</p><p>That’s why I built tmock . A strict, type-safe mocking Library.</p><h3>Case study: Catching a refactoring drift</h3><p>To show the power of tmock, let’s look at a common refactoring scenario. Imagine you have recently dropped an argument of type str from the get_by_id method of the UserRepository but have forgotten to remove the argument in your business logic (the process_user function).</p><p>After the refactoring, the test with MagicMock silently passes and fails to point out the problem. But the test with tmock fails fast and prints a nice error message pointing to where the problem is.</p><pre>from dataclasses import dataclass<br>from unittest.mock import MagicMock<br><br>from tmock import tmock, given, verify<br><br><br>@dataclass<br>class User:<br>    id: int<br>    email: str<br><br>class UserRepository:<br>    def get_by_id(self, user_id: int) -&gt; User: ...<br><br>def process_user(user_repo: UserRepository, user_id: int):<br>    # ❌ This line is a bug<br>    user = user_repo.get_by_id(user_id, &quot;Argument dropped after refactoring&quot;) <br>    ...<br><br>def test_with_magic_mock(): # 🤥 PASSES<br>    mock_repo = MagicMock(spec=UserRepository)<br>    mock_repo.get_by_id.return_value = User(id=123, email=&quot;alice@test.com&quot;)<br>    process_user(mock_repo, 123)<br>    mock_repo.get_by_id.assert_called_with(123, &quot;Argument dropped after refactoring&quot;)<br><br>def test_with_tmock(): # ✅ FAILS correctly<br>    mock_repo = tmock(UserRepository)<br>    user = User(id=123, email=&quot;alice@test.com&quot;)<br>    given().call(mock_repo.get_by_id(123, &quot;Argument dropped after refactoring&quot;)).returns(user)<br>    process_user(mock_repo, 123)<br>    verify().call(mock_repo.get_by_id(123, &quot;Argument dropped after refactoring&quot;)).once()</pre><p><strong>Why this matters:</strong></p><p>Because tmock enforces the actual method signature at runtime, it turns silent logic erros into loud, helpful tracebacks. It checks:</p><ul><li><strong>Argument counts: </strong>Capturing missing or extra arguments.</li><li><strong>Argument types: </strong>Ensuring the callers are sending the right types to the method.</li><li><strong>Return types: </strong>Validating that your stubs are returning the exact type specified in the method signature.</li></ul><p>tmock is available on PyPI. If you find the library useful, please give it a star on GitHub and share it with your team. If you run into any issues or have ideas for improvement, feel free to open an issue or a pull request.</p><p>🔗 <strong>GitHub: </strong><a href="https://github.com/soypedram/tmock">https://github.com/soypedram/tmock</a></p><p>📦 <strong>PyPI: </strong><a href="https://pypi.org/project/tmock/">https://pypi.org/project/tmock</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e2e5d7e9114" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Byte-Sized System Design]]></title>
            <link>https://medium.com/@pedram.esmaeeli/byte-sized-system-design-dff63c53bfcb?source=rss-62dc16552c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/dff63c53bfcb</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[diagrams]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Pedram Hajesmaeeli]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 06:19:31 GMT</pubDate>
            <atom:updated>2023-11-19T06:28:41.761Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bite-Sized System Design</h3><p>Welcome to the official repository for Bite-Sized system design! 🚀</p><h3>About</h3><p>Bite-Sized System Design is a tech-focused YouTube series where we break down complex coding concepts into digestible and easy-to-understand snippets. From coding enthusiasts to seasoned developers, our goal is to make tech talk accessible and enjoyable for everyone.</p><h3>Playlist Overview</h3><p>Explore our playlist for in-depth insights into various tech topics, coding challenges, and behind-the-scenes looks at designing cool projects. Each episode is a journey into the world of coding, presented in a casual and friendly format.</p><p><a href="https://www.youtube.com/playlist?list=PLOWT7w4Um9RPGvPDlJEtcqnCR26Dtx7z2">Byte-Sized System Design YouTube Playlist</a></p><h3>What to expect</h3><ul><li><strong>System Design Sessions: </strong>Watch as we sketch out architecture and high-level design of sample, real-world applications that handle millions of users.</li><li>Important Interview Questions: Prepare for the most common system design interview questions and learn how to approach them.</li></ul><h3>Design session — Pastebin</h3><p>In this episode of Bite-Sized Interviews, it’s just you, me, and a whiteboard as we dive into the design process of a pastebin.com clone. 🖥️✨ Get ready to join me in breaking down the steps, diagram-style, as we bring this concept to life. Whether you’re a seasoned coder or just starting out, this walkthrough is tailored for everyone. No fancy guests, just us geeking out over code and turning ideas into reality. Grab your favorite coding beverage, hit play, and let’s sketch out some tech brilliance together! 💻🎨</p><p>Watch the full explainer video here: <a href="https://www.youtube.com/watch?v=WjNdFldOoZA&amp;t=1s">https://www.youtube.com/watch?v=WjNdFldOoZA&amp;t=1s</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTdEbF4iKGmMhQq_sgslTA.png" /></figure><h3>Join our Community</h3><p>Subscribe to our <a href="https://www.youtube.com/channel/UCxO1-xEBZsM7CXm_uafbDig">YouTube Channel</a></p><p>Follow us on Twitter: <a href="https://twitter.com/__pdrum__">@__pdrum__</a></p><p>Star <a href="https://github.com/pdrum/byte-sized-interviews">the repository</a> on GitHub</p><p>Join our community as we embark on this tech-filled journey together! 💻🌐</p><p>Happy Coding! 🚀✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dff63c53bfcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang pitfalls]]></title>
            <link>https://medium.com/@pedram.esmaeeli/golang-pitfalls-f2ebae9c8208?source=rss-62dc16552c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2ebae9c8208</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[common-mistakes]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Pedram Hajesmaeeli]]></dc:creator>
            <pubDate>Thu, 18 Jul 2019 18:13:35 GMT</pubDate>
            <atom:updated>2019-07-19T06:48:57.564Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I will list some Golang pitfalls along with ways to avoid each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*U5vTyyz7HH3Dv4Wb.png" /><figcaption><em>Gopher</em> by <a href="http://www.reneefrench.com/">Renée French</a>, and <a href="https://github.com/tenntenn/gopher-stickers/">tenntenn</a> taken from <a href="https://talks.golang.org/2014/readability.slide">this talk</a></figcaption></figure><h3>Pointer to loop variable</h3><p>Take a look at the following piece of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a05799edfe3a07654e16f166f722444/href">https://medium.com/media/9a05799edfe3a07654e16f166f722444/href</a></iframe><p>It looks simple, it should print maximum value of ID in the list (which is 5). However the code prints 3. For figuring out why the bug happens we need to know a subtlety about how Golang for loops work. The variable that we called _ represents current index of iteration and the variable that we called p is current item in the list we are iterating on. Go uses only one variable for _ and only one variable for p . Then upon each iteration of the loop, value of those variables are updated. When our loop comes across person with ID=5 value of the variable max is set to a pointer to p . But we need to keep in mind that even though we don’t change value of max ever after, value of p itself is updated in each iteration and max is just a pointer to p. Therefore our code always returns a pointer to last person in the list!</p><p>In order to fix the bug, there are a couple of ways. One is to just use the index variable and change findMax function to look like the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09b8eedcf8983d6a03f2231604be7c3c/href">https://medium.com/media/09b8eedcf8983d6a03f2231604be7c3c/href</a></iframe><h3>Using goroutines on loop iterator variables</h3><p>Another mistake that is easy to make is using goroutines on loop iterator variables. The reason underlying it is very similar to what we saw in pointer to loop variable section. This pitfall is discussed in depth in <a href="https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables">Golang Wiki</a> you can refer to that page to find out code examples of how it happens and how to fix it.</p><h3>Arguments of defer statement</h3><p>Even though we use defer to execute a function when the surrounding function returns, there’s a subtlety to consider. We need to keep in mind that if defer keyword is followed by a call to a function that takes some arguments, those arguments are evaluated immediately.</p><p>Take a look at the following code for example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/222bfdcaea3b4ee3040ef8810427fa7d/href">https://medium.com/media/222bfdcaea3b4ee3040ef8810427fa7d/href</a></iframe><p>At first glance one may think must(doSth()) is defer till the execution of main function ends. Therefore you may expect the code to print Start followed byEnd but what the code actually prints is End followed by Start . This is because at runtime when go encounters the defer statement, it evaluates all parameters of the function call in front of defer immediately. For doing that it executes doSth() and keeps its return value as parameter to be fed into must . It then goes on executing rest of main. Finally it feeds nil which is the output of doSth into must function. As a result End is printed before Start . If our goal is to print End after Start one way to fix the snippet is to change our main function to look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/897121b0a3a2eab85b494d26bf88ed20/href">https://medium.com/media/897121b0a3a2eab85b494d26bf88ed20/href</a></iframe><p>This way the function call following defer does not have any arguments and must(doSth()) is run after main is executed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2ebae9c8208" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate swagger specification from Go source code]]></title>
            <link>https://medium.com/@pedram.esmaeeli/generate-swagger-specification-from-go-source-code-648615f7b9d9?source=rss-62dc16552c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/648615f7b9d9</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[documentation]]></category>
            <dc:creator><![CDATA[Pedram Hajesmaeeli]]></dc:creator>
            <pubDate>Sat, 29 Jun 2019 16:33:51 GMT</pubDate>
            <atom:updated>2019-06-29T19:06:03.821Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have some API written in Go for which you want to generate some fancy swagger specification, well this article is just about that!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B6FH5WmkQ7XjQJGG.png" /><figcaption>Created using gopherize.me</figcaption></figure><p><strong>Why swagger?</strong></p><p>We developers usually don’t enjoy that documentation part in our jobs that much. It looks boring, repetitive and not that enjoyable. However documentation is a “must” for any API. Here is why:</p><ul><li><strong>It improves user adoption</strong>. People use products they enjoy, as developer of APIs your end users are also developers. In order for them to enjoy your API and use it you need to provide them with good documentaion.</li><li><strong>It saves time and cost.</strong> Both internal and external users of your API need some onboarding to get started using your product. Poor or no documentation means more time spent onboarding those users and probably handling their frustration!</li></ul><p>So documentation is good but simply writing some markdown file is most of the time not enough. We want a tool that is standardized for the job, easy to share and descriptive enough. Well Swagger is the first such tool that comes to mind. It is kind of a de facto standard for documenting APIs.</p><p><strong>Why not just write it by hand?</strong></p><p>As developers we automate things. Well it feels natural to automate our own jobs as well, then.</p><p>Swagger docs are nice. For having one, all you need to do is to write a json or yaml file describing your API in term of URLs, requests and responses with a specific syntax. Then you will pass that specification to some other tool like swagger editor which will generate some amazing html and css out of it. In the following image you can see the specification on the left and the resulting documentation on the right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BNy7MHG1OFy85ubf.png" /><figcaption>A glance at a sample swagger documentation</figcaption></figure><p>Here’s what we gain by automating creation of swagger specification:</p><ul><li><strong>We will keep things simple (</strong><a href="https://en.wikipedia.org/wiki/KISS_principle"><strong>KISS</strong></a><strong>). </strong>As developers we use tools. A lot of tools. Each tool adds some complexity, so do we want to go deep into details of some new tool (namely Swagger)? Most probably not.</li><li><strong>We will avoid repetition (</strong><a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself"><strong>DRY</strong></a><strong>).</strong> Most probably you have defined some data structures in your code to which you will map requests and responses of your APIs. So why bother with rewriting them with another syntax in your specification? We have all seen the headache following that kind of repetition I guess. If we don’t eliminate that repetition the docs are far more likely to fall out of sync and it’s extremely harder to maintain them.</li></ul><p><strong>Comparison of two tools for generating the spec</strong></p><p>As of this writing the two dominant libraries for generating Swagger spec from go source code are <a href="https://github.com/swaggo/swag">Swag</a> and <a href="https://github.com/go-swagger/go-swagger">go-swagger</a>. Here I will discuss pros and cons of each and describe why I choose the second one.</p><ul><li>Where Swag wins: convenience. Swag is simpler. You just put some comments for your handlers and everything works out of the box. go-swagger is a little more complicated in terms of what you need to do in order for your spec to get generated.</li><li>Where go-swagger wins: Power. go-swagger gives you more power and flexibility to describe your API. It gives you more control over what gets generated.</li><li>Where go-swagger wins: Readability of code. With Swag each of your APIs have some very lengthy comments with lots of annotations preceding them. The comments are sometimes even longer than the code itself! But with go-swagger you can isolate those comments from your code. This way comments in your code can focus on people actually developing it and comments from which swagger spec is generated will be kept in its own specific package. Here’s what happens to your code if you don’t have that isolation of swagger-related comments:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*rBmVCNQri01ZsZuqUrXAUw.png" /><figcaption>How each endpoint will look like with Swag</figcaption></figure><ul><li>Where go-swagger wins: Popularity: go-swagger at the time of this writing has almost four times as many stars as Swag. It also seems better maintained and seems like it has less bugs. For example go-swagger supports representing 2D arrays in body of request/response while Swag does not. (at the time of this writing)</li></ul><p><strong>So how can I generate that spec?</strong></p><p>I will go through a case study describing how you can use go-swagger to generate your swagger specification. But before we start please note that in order for go-swagger to work, your package should be located correctly under GOPATH (even if you use go modules) and you should have a vendor folder containing your dependencies. I will describe this in more detail later.</p><p>Well… first you need to have an API. Here is a simple API that takes a POST request and returns a response. Bodies of both requests and response are JSON.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44762e55614dba32c0c997a301c7881c/href">https://medium.com/media/44762e55614dba32c0c997a301c7881c/href</a></iframe><p>Then we will create a separate package to hold the comments and structs written for the purpose of Swagger. We will name it docs . But before that in our main file main.go we need to add an import for our docs package. This is because without that import, the docs package is not imported anywhere in the code, therefore it will be ignored during the build. go-swagger starts looking for packages from main.go and follows is imports recursively. Therefore without such import there will be no docs for us! In our main file we also set up basic auth for all our endpoints.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73ba85ff8a69d0772cbcc6494eb6138c/href">https://medium.com/media/73ba85ff8a69d0772cbcc6494eb6138c/href</a></iframe><p>So now that we have a simple application up and running we can go for the docs package and see what should go in there. In order to give general information about our APIs as a whole (not any endpoint in specific) we need to create a file in our docs package and add a package comment like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5e993d7c3f7d03565a6d8648e587b7b/href">https://medium.com/media/f5e993d7c3f7d03565a6d8648e587b7b/href</a></iframe><p>The comments are self descriptive and the conventions for writing it are described <a href="https://goswagger.io/use/spec/meta.html">in this page</a>. In short, then name that follows Package classification in the first line is name of our web service. The line following it is description of our API. There are some more info and the whole thing ends with swagger:meta annotation. This results in this part of our docs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-I7s_Am1fsfv0qxfpiVxrw.png" /><figcaption>Output of meta annotation</figcaption></figure><p>Finally we document the foobar endpoint under docs package using just a few lines of comments and go code. Here is how it looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0574cbe4140be55c8b66525560b55cd/href">https://medium.com/media/d0574cbe4140be55c8b66525560b55cd/href</a></iframe><p>A few things to point out about this snippet are:</p><ul><li>swagger:route annotation is followed by an http method, a URL, a tag for that endpoint (endpoints with similar tags will be grouped together in resulting documentation) and an id for that endpoint. The id will be used for declaring parameters of the endpoint.</li><li>Line following swagger:route annotation is description of that endpoint. It should end with a dot in order for it to be properly displayed! If it ends with a dot it is displayed in summary of the endpoint in front of the url when the section for that endpoint is collapsed, otherwise it will only get visible when the section is expanded (not collapsed).</li><li>We define a struct for response body in case of success. We call it fooBarResponseWrapper . This struct has a single field called Body annotated with //in:body . Name of this struct does not make any difference. What matters is the name you put in front of swagger:response annotation. That name is used in responses section of swagger:route comments to indicate what response gets returned. Note that whatever comment you put above swagger:response annotation will be used as description of response body in docs. go-swagger will automatically figure out how JSON of api.FooBarRequest looks like and will display it in the docs.</li><li>We define a struct for parameters of requests called fooBarParamsWrapper . This specific endpoint has only a body parameter. (No path parameter or query parameter). Therefore the struct has a single field. Please note that the struct is annotated with // swagger:parameters idOfFooBarEndpoint This annotation is how go-swagger will figure out what endpoint there parameters belong to. The struct has a single field called Body annotated with // in:body . go-swagger will automatically figure out what JSON representation of api.FooBarRequest looks like and will show it in the docs. It will also take any comment directly above // in:body annotation as description of the parameter. Name of this struct is also of no importance.</li></ul><p>This is the docs that get generated for this specific endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOcYEdEyFlNKbtx5RL5a-g.png" /><figcaption>docs of foobar endpoint</figcaption></figure><p><strong>What commands do I need?</strong></p><p>First I should emphasize that you need to put your project under GOPATH properly.</p><p>If you already use vendor package, you are good to go, otherwise if you are using go modules run the following command to create one: GO111MODULE=on go mod vendor</p><p>Then go on and install go-swagger via:</p><pre>GO111MODULE=off go get -u github.com/go-swagger/go-swagger/cmd/swagger</pre><p>Finally to generate swagger specification and putting it in a file called swagger.yaml you need to run GO111MODULE=off swagger generate spec -o ./swagger.yaml --scan-models in the root of project.</p><p>To see the resulting documentation. (viewing the yaml file as a fancy webpage) you can run: swagger serve -F=swagger swagger.yaml</p><p>If the commands look complicated there’s a simpler way! Just create a file called Makefile in the root of your project and paste the following snippet into it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3da4bd5759ccbe7a5d9e50866c56b01/href">https://medium.com/media/f3da4bd5759ccbe7a5d9e50866c56b01/href</a></iframe><p>Then you can simply use make swagger to generate the spec (i.e. swagger.yaml) and use make serve-swagger to view the resulting docs in a browser. Also instead of using make serve-swagger you can paste your yaml file into <a href="https://editor.swagger.io/">swagger editor</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wq9lDFfFD9sd2FSxAr8XhA.png" /><figcaption>Result of running make servce-swagger</figcaption></figure><p><strong>Source code and go-swagger docs</strong></p><p>You can find source code of case study presented in this article <a href="https://github.com/pdrum/swagger-automation">HERE</a>. source code of go-swagger <a href="https://github.com/go-swagger/go-swagger">HERE</a> and you can visit documentation of go-swagger which describes all its features in great details using <a href="https://github.com/go-swagger/go-swagger">THIS LINK</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=648615f7b9d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A pattern for overcoming non-determinism of Golang select statement]]></title>
            <link>https://medium.com/@pedram.esmaeeli/a-pattern-for-overcoming-non-determinism-of-golang-select-statement-139dbe93db98?source=rss-62dc16552c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/139dbe93db98</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Pedram Hajesmaeeli]]></dc:creator>
            <pubDate>Fri, 03 May 2019 20:50:15 GMT</pubDate>
            <atom:updated>2019-05-03T20:50:15.637Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I will introduce a pattern that simulates behavior of select statement in go but without the non-determinism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*ohGLfDN_6toYcWhS.jpg" /></figure><p>There are cases when we have a goroutine which takes care of multiple similar tasks. For example in case of websocket we might have a hub goroutine that exposes a connect channel and a disconnect channel, both of type chan *Connection. Upon receiving a message from connect channel it keeps a reference to the connection somewhere and upon receiving from disconnect channel, it removes reference to the connection. In this case even though we are exposing two channels and handling two different types of events, we need to process events in order of their occurrence. It means that the event which has occurred sooner, should be taken care of sooner as well. Otherwise we may run into cases when for a specific connection, we handle disconnect event sooner than its corresponding connect event.</p><p>First thing that comes to mind for handling such cases is using a select statement inside a for loop. However there is an issue with that approach: Select statement provides no guarantee of order of execution. What it means is when multiple channels have some message in them, select statement does not necessarily pick the message that has arrived earlier, first:</p><p>&gt; If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection.</p><p>It is ok for many usecases, however there are times when we need to make sure the message that has come earliest, will be read first. In those cases we can not use select statements anymore. Recently I have found a workaround for this overcoming this problem.</p><p>Here is the code before applying the pattern. Note that on each iteration of for loop if connectChan and disconnectChan both have messages, select statement will just read one of them randomly. When deciding which channel to read from it does not care message of which channel has arrived earlier. Therefore we might run into the problem described earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AtkORSy2zJwruewgHedjpA.png" /><figcaption>Before applying the pattern</figcaption></figure><p>However there is a neat way to have that guarantee of order of execution with a small change. Instead of listening to two different channels, we can expose one command channel, along with a Command interface and get rid of the select statement. After applying the pattern, our code will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJB2cfjdkHSOVMubQELwTA.png" /><figcaption>After applying the pattern</figcaption></figure><p>Now all events will go through a single channel, therefore they will be processed in the same order as they have occurred. Beauty of this pattern in my opinion is that there is no switch-case anywhere in it. Therefore it is quite easy to add new types of commands. Conforming with open-closed principle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=139dbe93db98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Scrum distilled]]></title>
            <link>https://medium.com/@pedram.esmaeeli/essential-scrum-distilled-4d49ecf25fe3?source=rss-62dc16552c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d49ecf25fe3</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pedram Hajesmaeeli]]></dc:creator>
            <pubDate>Sat, 16 Mar 2019 21:09:08 GMT</pubDate>
            <atom:updated>2019-03-16T21:24:45.312Z</atom:updated>
            <content:encoded><![CDATA[<p>This writing explains core concepts of Scrum. The most widely-adopted agile methodology.</p><p>If you are a developer, product manager, designer or doing anything related to software development, you have probably heard of Scrum. There are several books written on the subject including Essential Scrum: A Practical Guide to the Most Popular Agile Process by Kenneth S. Rubin. However not everyone wants to take the time to read the whole book. Therefore in this article I am highlighting key parts of the book for those who want to quickly review or learn about Scrum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*P4GOs-EiPaDLWS2t.jpg" /><figcaption>Essential Scrum</figcaption></figure><h3>Roots and applicability</h3><p>Scrum has its roots in late 19s product development of Japan where it’s been used in companies like Honda, Canon and Fuji Xerox. However Scrum as a word comes from the game of rugby where it nominates a means of resuming the game after a minor infringement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*O7xPhmrSvj4NbZsH.jpg" /><figcaption>Scrum in Rugby</figcaption></figure><p>According to cynefin framework problems can be categorized to the following four types:</p><ul><li>Complex where one should probe, sense, respond</li><li>Complicated where one should sense, analyze, respond</li><li>Chaotic where one should act, sense and respond</li><li>Simple where one should sense, categorize and respond</li><li>Disorder where one does not know which of the aforementioned categories her problem lies in. Prople should just try to get out of this situation by breaking the problem to pieces each lying in one of the other categories.</li></ul><p>Scrum is a good fit for complex problems which constitute most of software engineering problems where one should build a new product based on ever-changing needs of customers. For complicated problems like optimizing performance of a component or simple problems, plan-driven, 3rd generation methodologies can be a better approach where one can plan more accurately. Scrum is also not applicable to chaotic problems where fast alternations in customer needs or the need to immediately fix defects does not leave room for all the ceremony involved in scrum. This is usually the case in maintenance of software. More lightweight approaches like Kanban better suit these kind of problems.</p><h3>The big picture</h3><p>Scrum is comprised of a set of roles, activities and artifacts and is a framework to which one can add her own practices to realize agile principles, hence it can be customized to meet one’s specific business requirements rather than being used as a rigid out of the box solution.</p><p>Scrum defines three roles:</p><ul><li>Product owner who represents customers and business team.</li><li>Scrum master Who acts as a facilitator, guiding the scrum team and leading it.</li><li>Scrum team who should actually develop the software product.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*em_6nrptrCAEO4eD.jpg" /><figcaption>Scrum Roles</figcaption></figure><p>The aforementioned roles get involved in Sprint, Sprint Planning, Sprint Execution, Daily Scrum, Sprint Review, Sprint Retrospective and Product Backlog Grooming. These activities result in Product backlog, sprint backlog and potentially shippable product increment.</p><p>As the concept of <em>sprint</em> is the most important constituent part of the process it is worth being discussed a bit more in this section. Sprints are time boxed intervals of a week up to a calendar month long in which scrum team builds a potentially shippable increment to the product. Each product is built after several releases and each release comprises several sprints. The process suggests a product backlog which holds some items (PBI or Product Backlog Item). These items are placeholders for a potential verbal discussion between product owner and the team and briefly describes essence of a feature which should be added or a defect that should get fixed. PBIs are prioritized and the ones which are closer to the top are more detailed and more small-grained. Hence we are leveraging just in time planning and adopting to the emergent changes rather than having planned everything soon in the development effort as is the case with waterfall approaches.</p><p>Each sprint starts with a short sprint planning session where the scrum team decides on the PBIs that should be included in the upcoming sprint and refines them to make a sprint baklog. The other result of sprint planning besides the sprint backlog is the sprint goal. Sprint goal can be viewed as a contract between the product owner and the development team where the product owner commits to not making any goal altering change during the sprint and the development team commits to having acheived the goal by the end of the sprint. The sprint backlog consists of tasks which should take couple of hours to get done by one or two developers. Then sprint execution begins when the cross-functional, self-organized development team takes the tasks from the sprint backlogs and attends to them. Each day during the sprint execution the team holds a short stand-up-meeting which is also called the daily scrum through which they answer the following questions:</p><ul><li>What they did in that day.</li><li>What they plan to do the next day.</li><li>Whether there was any problems.</li></ul><p>Not everyone gets the chance to talk in the daily stand up meetings. The ones who are commited to sprint goal are the ones who actually talk and the ones who are just involved in the goal rather than being committed to it are just observers.</p><p>As a result of sprint execution at the end of a sprint what gets built is a potentially shippable product increment which conforms to the predefined definition of done.</p><p>Each sprint ends with sprint review and sprint retrospective. The latter is an effort to improve the applied process and the former is an effort to fix the defects in the sprint that has just finished so that the same problems will not occur over and over again.</p><h3>Agile principles</h3><p>Agile approaches when applicable have several advantages over plan-driven waterfall approaches. This advantage is a consequence of conforming to some princples. The rest of this section categorizes those principles and describes each one briefly</p><h4><strong>1 — Variability and uncertainty</strong></h4><ul><li><strong>Embrace helpful variability</strong>: Variability is what differentiates development from manufacturing. The emergent knowledge about the product and the evolving needs of customers is what should get the development effort. So the team should adopt with changes.</li><li><strong>Employ iterative and incremental development</strong>: Rather than planning things upfront and making assumptions for what we do not know we employ a planned rework strategy where we accept the risk of being wrong but we probe and respond to customers&#39; feedbacks. It should be mentioned that trying each iteration should have some requirements analysis, some analysis, some design and some implementation. Otherwise our process will decrease to what some have called waterscrum or scrumfall which has the same problems as the waterfall approaches.</li><li><strong>Leverage variability through inspection, adoption and transparency</strong>: Fast feedback cycle and the envolvement of all stakeholders in the development effort along with early and frequent releases allows for inspection of variability and adopting to it.</li><li><strong>Reduce all forms of uncertainty simoltaneously</strong>: We have three forms of uncertainty:</li><li><strong>End uncertainty</strong>: Uncertainty about what gets built</li><li><strong>Means uncertainty</strong>: Uncertainty about how the product gets built</li><li><strong>Customer uncertainty</strong>: Uncertainty about who the users of the product actually will be Rather than trying to eliminate one type of uncertainty before embarking on the other, one should try to reduce them all simultaneously.</li></ul><h4>2 — Prediction and adoption</h4><ul><li><strong>Keep options open</strong>: Important decisions must be made at the last responsibility moment (ie. last moment when the cost of deferring the decision is more than the price of making one)</li><li><strong>Accept that you can&#39;t get it right up front</strong>: Knowledge of the system and awareness of customers about what they really need are at their minimum when nothing has been done yet. So one should avoid trying to make detailed decisions or gather detailed requirements at that moment.</li><li><strong>Favor an adoptive, explorative aproach</strong></li><li><strong>Embrace change in an economically sensible way</strong>: In scrum excessive artifacts do not get created up front hence it is cheaper to make changes as project goes on as compared to waterfall approaches</li><li><strong>Balance predictive up-front work with adaptive just-in-time work</strong></li></ul><h4>3 — Validated learning</h4><ul><li><strong>Validate important assumptions fast</strong>: Assumptions represent a significant development risk so they should be validated as soon as possible.</li><li><strong>Leverage multiple concurrent learning loops</strong>: Daily scrum is a daily learning loop where as sprint review and retrospective are the learning loops at sprint level.</li><li><strong>Organize workflow for fast feedback</strong>: Fast feedback allows for faster discovery of mistakes and lower costs</li></ul><h4>4 — WIP</h4><ul><li><strong>Use economically sensible batch sizes</strong>: It is better to keep the amount work in progress small and reduce its variation.</li><li><strong>Recognize inventory and manage it for good flow</strong>: Inventory in manufacturing is pieces that should get assembled to build up the product whereas in software development inventory is the work in progress. A company will face large losses if it tends to buy a large inventory and then find out it does not need half of it. Similarly in case of software development it is more expensive to make changes if the inventory is big since the change has more severe effect on what has already been built and what is getting built as compared to when the inventory size is small.</li><li><strong>Focus on idle work not idle workers</strong>: One should not try to increase utilization of workers by getting them involved in multiple projects since it results in works being idle due to the worker being busy with other projects which is more harmful.</li><li><strong>Consider cost of delay</strong>: Sometimes revenue made by deploying product sooner makes it worth spending some extra money to get the job done sooner. For example if a company employs a documenter who is not fully utilized during the project, it may end up having more financials advantages than the case where the documenter is employed at the end of the project when everything but the documentation has been done. Documenting at that time results in delay of deployment which in turn may have bad financial consequences</li></ul><h4>5 — Progress</h4><ul><li><strong>Adopt to real-time information and replan</strong></li><li><strong>Measure progress by validating working assets rather than conformance to plan</strong></li><li><strong>Focus on value-centric delivery rather than intermediary artifacts</strong></li></ul><p><strong>6 — Performance</strong></p><ul><li><strong>Go fast but never hurry:</strong> So that quality is not sacrificed for speed</li><li><strong>Build in quality:</strong> Things like integration and testing should not be left for the end of development and technical debt must be avoided.</li><li><strong>Employ minimally sufficient ceremony</strong>: Documentation is good to do only when it is valuable to customer, captures important decisions or helps new team members come to collaborate.</li></ul><h3>Sprints</h3><p>Sprints should be time-boxed and have short, consistent durations. Consistent duration leads to ease of scheduling sprint events and ease of synchronizing teams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*c7OOe8Xth7dm2xYW.jpg" /><figcaption>Sprints</figcaption></figure><p>In the course of a sprint no goal-altering change must be encountered. Any such change is a violation of the commitment between product owner and the team and hence has long-time consequences. However sometimes business environment makes such changes unavoidable. In these cases (which are rare) the development team usually understand the product owner.Also sometimes abrupt changes in environment variables makes the rest of sprint pointless. In such cases the sprint comes to an abnormal termination. The next sprints either has its normal length, extends to contain the time left from current sprint or is shortened to end when the current sprint was supposed to.</p><p>the increment built in each sprint should be in conformance with the predefined definition of done.</p><h3>Requirements and user stories</h3><p>Scrum suggests product backlogs and sprint backlogs for capturing requirements but does not specify any format for the items that get placed in them. User story is the format that most people use. User stories are cards that have small dimensions and serve as place holders for a potential verbal conversation. They represent the essence of a feature or an issue to be solved in the form of:</p><blockquote><em>As [</em>userRole<em>] I want to [</em>target<em>] so that [</em>reason<em>]</em></blockquote><p>The reason part is optional but it is a good practise to include them unless it is too obvious to mentioned. User stories can have multiple levels of granularity and are progressively refined and broken down to smaller stories.</p><p>User stories can be categorized by the following categories based on their granularity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*-ES82Y8MMtZlzDh2EsqIQg.png" /><figcaption>Types of user stories</figcaption></figure><p>Similar sprintable stories can be tagged with a theme.</p><p>Quality of user stories can be assessed based on INVEST criteria which stands for:</p><ul><li><strong>Independent</strong></li><li><strong>Negotiable:</strong> Implementation details must be avoided in user stories.</li><li><strong>Valuable:</strong> All user stories should be of value to customers or the business so stories that are only of clear value to the development team should be avoided unless when product owner knows about what advantages those stories provied to the business.</li><li><strong>Estimatable</strong></li><li><strong>Sized appropriately</strong></li><li><strong>Testable</strong></li></ul><p>One approach towards preparing user stories is story writing workshops where internal and external stakeholders and the development team come together to prepare the user stories. Story mapping can be leveraged to increase the quality of such workshops. In story mapping each story is broken down to some smaller stories which are aligned horizontally based on their order of occurrence and vertically based on their importance.</p><h3>Product backlog</h3><p>Items in the product backlog are either features, defects, technical work(non-functional requirement) or knowledge acquisition activity. The latter too are only allowed when their business value of well understood by product owner. Quality of product backlog is assessed via DEEP criteria which stands for:</p><ul><li><strong>Detailed appropriately:</strong> Balanced between excessive pre-planning and lack of required information must be considered.</li><li><strong>Estimated:</strong> Items of portfolio backlog and items far from top of product backlog are estimated using T-shit size values, the ones near the top of product backlog are sized using either ideal day or story points and the ones in sprint backlog are estimated using ideal hours</li><li><strong>Emergent:</strong> Product backlog must be progressively refined in course of development</li><li><strong>Prioritized</strong></li></ul><p>Quality of product backlog improves overtime through grooming. Grooming is the responsibility of product owner but it is usually done as a collaborative effort so that ideas are shared and many potential misunderstandings are avoided. Scrum does not prescribe a specific time for product grooming but it usually takes place either upfront in release planning, in workshops during the sprint, after daily scrum or during sprint review. PBIs may have a definition of ready much like the definition of done which gets defined for the sprint.</p><p>Product backlog facilitates flow management. Release flow management is performed by drawing horizontal lines in the product backlog which separate releases and other lines within PBIs of a release that categorize PBIs vased on MOSCOW rules. PBIs also control the flow of sprints. Too many well detailed PBIs may incur waste when the team faces change and too few well detailed PBIs hinder performance of sprint. Backlogs usually contain two or three sprints worth of sprintable stories.</p><p>How many backlogs are used for a project differs from one to another. In large projects where hierarchical backlogs are leveraged where each backlog correspond to a constituent part of thhe project and is undertaken by multiple teams. In some cases multiple teams get assigned to a single backlog, whereas in other cases one team may get assigned to multiple projects (potential violation of idle worker rather than idle workers principle).</p><h3>Estimation and velocity</h3><p>Estimation of PBI sizes can be performed through planning poker where each member of team has a set of cards with cards which are numbered using some modified version of fibonacci sequence corresponding to story points that a member thinks suites a specific PBI and some special purpose cards that are numbered with PI, infinity and zero. For each PBI the game begins with product owner cclarifying the PBI and goes on with people deciding on the number of story points for each PBI, after the cards are played the players discuss conflicts and go on playing till they reach consensus on the matter.</p><p>Velocity can then be calculated based on the number of story points that a team completes in course of a sprint, Team’s velocity is typically represented by a range consisting of minimum and maximum expectable velocity of team. Velocity helps in release planning by facilitating calculation of number of sprints required for the release. In sprint planning since it facilitates choosing the set of PBIs that the team can commit to. In sprint execution, review and retrospective as a diagnostic metric. However misuse of velocity to blame or compare teams results in story point inflation or taking shortcuts which results in long-term side effects.</p><h3>Technical debt</h3><p>Technical debt can be a result of pressure to meet deadlines, attempting to falsely accelerate velocity, previous debts that prevent construction of new high-quality components, avoiding good practices such as TDD and can have three types:</p><ul><li><strong>Naive</strong>: Result of avoiding best practises.</li><li><strong>Unavoidable</strong>: Result of changes that invalidate past decisions.</li><li><strong>Strategic</strong>: As a means of taking competitive advantage, surviving in business, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ihVsuAAHPPXKhDfX.png" /><figcaption>Technical debt</figcaption></figure><p>Naive technical debt should be avoided and when accruing technical debt consequences of such debt should be clearly understood. Those consequences typically consist of:</p><ul><li>tipping point will be unpredictable and changes may have terrible effects on the system in some cases.</li><li>Time to delivery is increased</li><li>Number of defects increases</li><li>Development and support costs will increase</li><li>Product will deteriorate since it may no longer be able to embrace changes</li><li>Overall predictability will decrease and it will be harder to plan.</li><li>It will lead to decreased expectations and underperformance</li><li>It will lead to everyone including business people, developers, etc to feel frustrated by the defects.</li><li>Customer satisfaction will decrease</li></ul><p>in order to avoid those consequences when a developer happens to confront a technical debt that has not been known to exists before, in a piece of code she is working on she should try to refactor the piece of code until a specific threshold. If not all problems are resolved she should just move mention the debt in the issue tracker or technical debt backlog in order for it to be addressed sone time in future. She should also make sure to develop high-quality product so that technical debt is not increased further. This way each developer tries to conform to the boy scouts rule.</p><p>It is worth to mention that not occurrences of technical debts should be addressed. Specifically when the product has a very short life span, is a throw-away prototype or is near the end of its life, technical debts in it can simply get ignored.</p><h3>Conclusion</h3><p>This article briefly covers core principles of Scrum. However each concept can be discussed in much more details accompanied with more fine-grained techniques. Those details are out of scope of this writing. For further reading on those topics, you can refer to the book.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d49ecf25fe3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Rest Framework test and documentation]]></title>
            <link>https://medium.com/@pedram.esmaeeli/django-rest-framework-test-and-documentation-ffb351f07f87?source=rss-62dc16552c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffb351f07f87</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Pedram Hajesmaeeli]]></dc:creator>
            <pubDate>Mon, 17 Dec 2018 18:29:17 GMT</pubDate>
            <atom:updated>2018-12-17T18:29:17.102Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I am going to write about a testing library I developed called drftest. The idea is instead of writing API documentations manually we can have a tool that generates it based on our tests. Saving us time both in creating and maintaining the docs.</p><p>When writing a lot of APIs, it becomes hard to document them and to keep the document up to date over time. Using things like Swagger, one has to redeclare many of the database models as json schemas in the docs in order to be able to use them for demonstrating input/output of the API. This redeclaration makes the docs hard to maintain. Another thing I couldn’t do with Swagger is showing exactly what input results in what output. Therefore I couldn’t show the behavior of API in edge cases very well using Swagger.</p><p>Considering the time and effort it takes to keep Swagger docs up to date, I found it not suiting my needs in many cases. Once I was reading sth about <a href="http://agilemodeling.com/essays/executableSpecifications.htm">agile modeling</a> and this sentence caught my eye:</p><blockquote>With a <a href="http://agiledata.org/essays/tdd.html">test-driven development (TDD)</a> approach, part of the overall <a href="http://agilemodeling.com/essays/amdd.htm">Agile Model Driven Development (AMDD)</a> approach, your tests effectively become detailed specifications which are created on a just-in-time (JIT) basis.</blockquote><p>I found this idea absolutely helpful and also relevant to the problem I had. I was already describing every detail of the API in tests so I thought “why am I doing it all orver again in the docs? Is there a way to make some changes so that I can actually use these tests as API documentation too?”.</p><p>Overtime I had developed some testing tools in order to facilitate writing tests for Django Rest Framework APIs and it was being used in the project I was working on. Initial utilities I had developed where some methods that eliminated some boilerplate code in tests and helped to keep them DRY . I decided to change those utilities in such a way as for them to record all requests that are made during tests and also to record what response the API returns for each request. Therefore at the end of running tests, I had a data-structure which had kept track of every request/response made during tests.</p><p>Initially I used the aforementioned data-structure to create a json file and wrote a small react app to render that file. But I didn’t find the resulting docs beautiful enough. Instead of trying to make the UI more beautiful I thought that I am most probably wrong in not using a more mature tool for displaying the result. After all documentation is sth for which a lot of tools are already built. After some search I found <a href="https://mkdocs.org/">mkdocs</a> interesting for replacing my handmade UI. In order to use mkdocs my code had to output markdown files instead of json. I made some changes in order to achieve that.</p><p>The resulting documentation shows names of subsystems of the code (i.e. Django apps) in the navbar, upon clicking on the name of each app in the navbar, user sees list of test classes in that app on the sidebar. Each test class corresponds to one endpoint under test. For each test class there is a listing of which test cases exist for that class and therefore what response the endpoint generates for each request. Also docstrings of test classes and test methods are made available through the docs. Using docstrings of test classes, one can describe what purpose each endpoint serves and using docstrings of test methods one can describe why a particular request results in a particular response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BGqV-PfRgXq6NsxXXZKOg.png" /><figcaption>A glance at the resulting documentation</figcaption></figure><p>The following code snippet shows how easy it is to write tests using drftest. Things like user authentication, RequestFactory, APIClient, etc are all taken care of by drftest and not repeated in every single test case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGQdeDpk-xgOkQq1SJHv7g.png" /><figcaption>Keeping tests DRY using drftest</figcaption></figure><p>After using DRF Test we gained a lot in terms of time spent on creating and maintaining API docs and also found it easier to write tests for our APIs thanks to its utility methods for sending requests. It helped make communications inside the team more effective and the overall process more agile. Therefore I decided to publish it on Github. I hope it may be useful to others as well. A live demo of documentations generated by drftest is available through <a href="https://drftest.netlify.com/todo/">this link</a>. The project is hosted on <a href="https://github.com/pdrum/drftest">this repo on github</a>. I also made <a href="https://github.com/pdrum/drftest_example">another repo</a> which is a very simple project consisting of a todo API that shows how drftest can be used in a Django project.<br>I welcome any new ideas and contributions to make the project better. Also in case you found this library helpful, creating similar libraries based on this idea for other frameworks and languages might be a good idea.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffb351f07f87" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>