<?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 Julia Suarez on Medium]]></title>
        <description><![CDATA[Stories by Julia Suarez on Medium]]></description>
        <link>https://medium.com/@jsilversun?source=rss-d1eb5173ac04------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Y5f4A_QZLK4RlszVcmQwAw.jpeg</url>
            <title>Stories by Julia Suarez on Medium</title>
            <link>https://medium.com/@jsilversun?source=rss-d1eb5173ac04------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:23:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jsilversun/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[How to run odoo tests with Pycharm]]></title>
            <link>https://medium.com/plusteam/how-to-run-odoo-tests-with-pycharm-51e4823bdc59?source=rss-d1eb5173ac04------2</link>
            <guid isPermaLink="false">https://medium.com/p/51e4823bdc59</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[odoo]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[pycharm]]></category>
            <dc:creator><![CDATA[Julia Suarez]]></dc:creator>
            <pubDate>Wed, 19 May 2021 13:59:57 GMT</pubDate>
            <atom:updated>2021-05-19T13:59:57.292Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>There is an example repository with an addon and all the scripts mentioned here: <a href="https://github.com/JSilversun/odoo-testing-example">https://github.com/JSilversun/odoo-testing-example</a></blockquote><p>If you are an odoo developer, you probably would like to write some unit tests like regular pytest/unit test suites so you can debug, get coverage reports and enhance your own developer experience.</p><p>So, how can we achieve it?</p><p>Well, let’s start by using a docker-compose file to get our odoo and database running:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f872cb2a318180e6437496ad4c9d3086/href">https://medium.com/media/f872cb2a318180e6437496ad4c9d3086/href</a></iframe><blockquote><strong>Note</strong>: The <em>--dev all</em> args will allow your odoo instance to restart once it detects changes on your addons or related volumes code.</blockquote><p>And a Dockerfile like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2313c9faf8b4e31177acd70cf3c9d18a/href">https://medium.com/media/2313c9faf8b4e31177acd70cf3c9d18a/href</a></iframe><p>In this file we see how we extend an odoo image, we install some packages like pytest-odoo coverage and pytest-html to generate coverage reports and run odoo’s tests with Pycharm. Also, a coverage directory is created with proper permissions so the coverage files can be copied from the docker container to the host machine later.</p><p>Now we run:</p><pre>docker-compose up -d</pre><p>And we will see the following containers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*av--vwk_YWf5fXrQoGnpNA.png" /></figure><p>Now we can go to http://localhost:8069 and we will see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jctx3vnPvi0Ns49y-gbTuw.png" /></figure><p>Feel free to change the connection details, just make sure you remember them.</p><p>At this point you will have your odoo instance running, you were able to use a docker compose to start an odoo instance with a Postgres database, it’s easy to change the odoo version you need with the image tag.</p><p>Now the question will be, if we have the odoo instance running in a docker, how can we run the tests?</p><p>I created a Makefile to teach you how to generate coverage reports or set up a database only for testing purposes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85c3ceaa4078c2ed6e7e583f33e9eee8/href">https://medium.com/media/85c3ceaa4078c2ed6e7e583f33e9eee8/href</a></iframe><p>First, we need to set up a database only to run the test so we don’t use the main database we use for our manual development, you can run make init_test_db to create a test database or reset it.</p><p>Start by connecting to the container using:</p><pre>docker exec -it plusteam-odoo-web bash</pre><p>Now you can run:</p><pre>odoo --help</pre><p>This is the odoo binary, if you take a look at all the options it provides, you will be able to see a test section with all the flags available.</p><p>Run the tests with:</p><pre>odoo --test-enable -d db_test -p 8001</pre><blockquote><strong>Note</strong>: Since the docker container for odoo is running the server already, you can specify a different port with the -p flag so you won’t get an error Address already in use.</blockquote><p>This is the “default” way to run odoo’s test, however, since this runs in a docker container, it can have a terrible developer experience since you can’t use your IDE to debug them.</p><p>So, how can we run our tests using Pycharm?</p><p>Go to Settings &gt; Project &gt; Python Interpreter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cz6TCRKxMSqRwa4oJMCeSw.png" /></figure><p>Add a new python interpreter, select docker, and specify the image name of the service. If you can’t find the image name for your customized odoo image you can generate an image with a name like this:</p><pre>docker build -t &lt;image_name&gt; .</pre><p>Now you will have a local image that will appear in the dialog mentioned previously. You can rename it if for some reason you need to invalidate the cached image.</p><p>A summary of how remote interpreters work in Pycharm: They will use the image name to launch a docker container anytime you run something through your IDE, for example:</p><p>When you open the Python console of your IDE like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c4g5RaRqD34q3KD9.png" /></figure><p>Pycharm will start a docker container based on the image you provided:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oAeoXihQUHxza2D7.png" /></figure><p>This is why the image used needs to have available pytest-odoo so we can run our tests later.</p><p>This container was started automatically by Pycharm as soon as you open the python console, the same will happen if you having any python script using a remote interpreter.</p><p>You can connect to the docker container as you would do with any kind of container like this:</p><pre>docker exec -it &lt;container_name|container_id&gt; bash</pre><p>Then you will realize that your container looks a bit different than you might expect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b8EmgjUSlCstXVIr.png" /></figure><p>As you can see all the project code is available in the docker container by default.</p><p>Now to we need to add a config to run our tests with Pycharm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/0*BP9vY6L3Zx1sfM1e.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fmUUvFRSVb4kUYaX.png" /></figure><p>It’s important to note that Pycharm won’t use the volume bindings specified in the docker-compose file, this means the odoo.conf file from the config folder won’t be copied to the folder odoo expects and this leads to problems when we run our tests because odoo won’t know where the addons are located, to solve this, we specified an odoo.conf file used only for tests which main difference is mapping the addons path to /opt/project/addons since this is the directory where Pycharm will copy the entire project’s code by default.</p><blockquote>Note: Review your database connection to make sure the odoo.test.conf has proper credentials for the test database.</blockquote><p>With these settings now our tests work as expected!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3KN63RPgwiF41qlUAbpSig.png" /></figure><p>We can even debug our tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKs8kXt9XFOYXfxYHsBHHQ.png" /></figure><h3>Coverage</h3><h4>Coverage for custom addons</h4><p>Since we use pytest to run our odoo tests, we can use it to generate html reports as well, I created a command to make this process easier. Please note that this will only consider the tests inside your custom addons, since I don’t know yet how to tell pytest to run all the tests inside odoo’s binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4tI995sdt-HLvbLn.png" /></figure><p>How it looks like when you run the script</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/0*sTS8rlcepk5ZXzkJ.png" /></figure><p>After the script finishes, you will get the report in the coverage/local folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fK0lLtnEtNT8UyGN.png" /></figure><p>This is how the pytest report looks like.</p><h4>Coverage for all tests</h4><p>I also read about how can I can generate a coverage report for all tests even the ones inside odoo’s binary.</p><p>The process is similar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qVM6zXw8praU3-XN.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CSCUCDa_6QHHCEsT.png" /></figure><p>However this process will take more time, once it’s done, you can see the html report in the coverage/all folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/0*D0N1P2sGWqeia_cq.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ocwJJZZyjYZh0q2F.png" /></figure><p>This is how the report looks like.</p><h3>Conclusion</h3><p>Hope this article was useful to enhance your developer experience with odoo, docker definitely changes the way developers work since we can have open source projects running with few lines of code in a docker-compose file and even better, we can customize images to add things missing like libraries to allow us running tests.</p><p>Pycharm’s remote interpreters is an amazing feature that lets us take full advantage of docker images to debug or run scripts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51e4823bdc59" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plusteam/how-to-run-odoo-tests-with-pycharm-51e4823bdc59">How to run odoo tests with Pycharm</a> was originally published in <a href="https://medium.com/plusteam">plusteam</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building your landing]]></title>
            <link>https://jsilversun.medium.com/building-your-landing-99db1ceeb0cf?source=rss-d1eb5173ac04------2</link>
            <guid isPermaLink="false">https://medium.com/p/99db1ceeb0cf</guid>
            <category><![CDATA[bundle-size]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuetify]]></category>
            <category><![CDATA[landing]]></category>
            <dc:creator><![CDATA[Julia Suarez]]></dc:creator>
            <pubDate>Wed, 05 May 2021 16:20:52 GMT</pubDate>
            <atom:updated>2021-05-05T16:56:45.089Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a landing page was one of my 2021 resolutions, however, I usually get caught up working too much on different projects and I never find the time to do things for myself, it’s time to be different, time to do what you promise, and give that step to actually move forward to achieve your goals.</p><blockquote>You can see the final result here: <a href="https://juliasuarez.dev/">https://juliasuarez.dev/</a> and the source code is available at: <a href="https://github.com/JSilversun/js-landing">https://github.com/JSilversun/js-landing</a></blockquote><p>The first question I had was, <strong>what should I use to build it</strong>? Since the structure is so generic, maybe using WordPress was the right call since I could find nice <a href="https://themeforest.net/category/wordpress?page=2&amp;term=cv#content">templates for 12 — 60$</a> depending on the one I chose.</p><p>I knew that using a pre-made template was going to save me a lot of time, I have some WordPress experience so it would be easy to just go and fill in the information, but in the end, I chose not to do it. Why? To be honest, I’m a prideful person, and as soon as I liked one template I knew I was going to be unhappy with the result.</p><p>It’s funny because when you are building software you are always using all kinds of abstractions, nobody really builds anything from scratch, otherwise, we would use ones and zeroes for that matter. Besides nobody usually cares what you use to build a website if it looks good enough, functions properly, and doesn’t have overwhelming performance issues.</p><p>However, it’s important to understand your needs, I’m a person who likes to change everything if got a better idea in mind, which means I appreciate customization over initial speed by something prebuilt, you can satisfy this need by using plugins like <a href="https://elementor.com/">Elementor</a>, but it comes with paid limitations for advance components.</p><p>A final reason to chose using a frontend framework is that I wanted to face my own limitations and figure out what I could come up with, Am I as good as I think I’m? How long will actually take me to build it? How well will it score regarding performance, SEO, and style? I wanted an answer to all of these questions. So, let&#39;s get them!</p><h3>Technology stack</h3><p>I picked Vue and Vuetify (UI component framework) for the frontend development since these are the ones I have more experience with. For the hosting, I chose firebase since it comes with a great free plan and they had different products like Firestore, Cloud functions, etc just in case I needed them.</p><p>So, having this decided, I just needed to figure out a website structure that looked good enough, so I looked for a lot of templates on <a href="https://themeforest.net/">themeforest</a> and <a href="https://dribbble.com/">dribbble</a> to gather inspirations, I recommend these sites if you are looking for design ideas.</p><p>In about a week I had a website structure I actually liked, so building a landing page wasn’t that complicated, however, it took me like one week to test different ideas for the animations. During this kind of development, it’s easy to wander over things that in the end don’t really matter, for example, most of the early animations I tested never got to the final landing page, however, I did learn a lot.</p><p>I came across an interesting animation library called <a href="https://animxyz.com/">AnimXYZ</a>, they supported Vue and React and after reading their documentation they have a <a href="https://animxyz.com/docs/#practical-examples">Practical Examples</a> section, I really like them, you can actually see how your application comes to life!</p><p>Up to this point, I had an initial version with responsive design and basic animations, the next step was developing the content because <strong>it’s not the same to read a bunch of lorem ipsums with placeholders than seeing yourself and what you actually want to say or show</strong>, I figured once I had the content I would realize if I wanted to add more sections or modify the existing ones.</p><p>Can you guess what part took me more effort? Yes, the hero section! Why? Because I needed skills that I don’t currently have like photography for websites or photo editing, I spent 3 days taking like 200 pictures and hating all of them, the first night I wasn’t able to sleep because this was taking more time than I was expecting and I didn’t see actual progress.</p><p>You might take a look at the landing page and say the image is too simple, but usually simple things have a lot of work behind them, the main problem was taking a photo that actually has a nice background for the text, otherwise, it wouldn’t be readable, I didn’t want a complicated image edition over the hero section because this would mean I couldn’t change it regularly.</p><p>So, I learned the basics of Lightroom on how to fix lighting issues and then I realize it was easier to be more careful on taking the photo than actually editing it, I was lucky that I have a gray room it went great with the overall tones of the page.</p><p>The next step was to buy a domain! <a href="https://www.namecheap.com/">Namescheap</a> has great prices, but this was the first time I was actually buying and maintaining a website so I didn’t know if I had to code some script to manage the certificates, fortunately, this wasn’t the case since <strong>firebase manage the certificate renewal on their own</strong>, so once you buy the domain and link it in the firebase hosting section, you will get nice https protection for <strong>free</strong>. To learn more about firebase and custom domain <a href="https://firebase.google.com/docs/hosting/custom-domain">read their docs</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBDNGI_RyaoMkG1BdVTBlA.png" /><figcaption>Firebase hosting section to set up your custom domain</figcaption></figure><h3><strong>Optimization</strong></h3><p>Once I got my domain, content, and structure ready to go, it was time for the last phase, facing the judge, the dragon, <strong>lighthouse</strong>! I was excited because I was careful of minimizing my dependencies and every time I added a new one I used <a href="https://bundlephobia.com/">bundlephobia</a> to check they weren’t a deal-breaker.</p><p>I used 3 sites to test the performance of my website:</p><ol><li><a href="https://www.webpagetest.org/">WebPageTest</a></li><li><a href="https://developers.google.com/speed/pagespeed/insights/">PageSpeed Insights</a></li><li><a href="https://web.dev/measure/">Measure.dev</a></li></ol><p>Mainly WebPageTest and PageSpeed Insights helped me improve different areas, the first test wasn’t good at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRWe_j_hnKMEUuJZqiKwyg.png" /></figure><p>We can notice how some images really delay the page load, so I started there, how to optimize images? I needed to automate the thumbnail generation and use smaller sizes.</p><h4>Optimizing images</h4><p>My first idea was to use firebase cloud functions and firebase storage, something like when I upload an image to firebase store, use a cloud function to generate an optimized thumbnail. It looked simple enough, however, it felt quite manual. I used a library called <a href="https://www.npmjs.com/package/sharp">sharp</a>. This was the main code for the firebase function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*WnZhaJLTEKwBKGirpnoolg.png" /></figure><p>I realized I needed not just the thumbnails but the main image to be optimized as well since several of them are pictures taken from a phone and those are way too heavy for any website.</p><p>After each upload, generate a thumbnail and an optimized version of the image with a maximum size, then delete the original image from firebase storage since is not needed.</p><p>However, I was coding this without too much care and I end up with a crazy recursion one day:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksSWnncWNanmug4s8LV1jg.png" /></figure><p>I laughed a lot that day, fortunately, I was able to take down the firebase function quickly before any charging problem, it was a bug when analyzing the file name to see if it was a thumbnail to avoid generating a thumbnail from the thumbnail.</p><p>I read many articles about thumbnail generation, it wasn’t fun having to deal with that, figuring out the right parameters for sharp to get the absolute best image size without jeopardizing the quality.</p><p>I even learned that <a href="https://www.gatsbyjs.com/plugins/gatsby-plugin-image/">gatsby</a> a framework for React comes with a plugin for automatic thumbnail generation and for once I questioned my Vue decision, I considered alternatives for Vue like <a href="https://nuxtjs.org/">Nuxt</a> or <a href="https://gridsome.org/">Grindome</a> but I didn’t want to add more dependencies or deal with new framework learning curves just to optimize my images. Then I found out about <a href="https://cloudinary.com/">Cloudinary</a>. It was like finding an oasis in the middle of the dessert.</p><p>Cloudinary allows you to upload your images like you would do with firebase storage, and then in the image URL you can request an optimized version of your image, they transform your image and deliver it to you on-demand, the first time is considered a transformation and then they cache your image for further deliveries, they work as a CDN too so the image responses and sizes were pretty fast.</p><p>To give you an example I had this landing image with a size of 800kb approx.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bKa9y4yhBPNiUp_0j-QL3w.png" /></figure><p>Now if you request the raw image, you will see a slow network performance:</p><blockquote><a href="https://res.cloudinary.com/jsilversun/image/upload/v1618318936/landing/portfolio/landing/landing.png">https://res.cloudinary.com/jsilversun/image/upload/v1618318936/landing/portfolio/landing/landing.png</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1e-IiXON_t55Xbi5aaGvCQ.png" /></figure><p>Now let’s say we want an optimized thumbnail, we would need to change the URL like this:</p><blockquote><a href="https://res.cloudinary.com/jsilversun/image/upload/w_500,q_auto,f_auto/landing/portfolio/landing/landing">https://res.cloudinary.com/jsilversun/image/upload/w_500,q_auto,f_auto/landing/portfolio/landing/landing</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQ8xsgv6gk8Pxujc_kCw6A.png" /></figure><p>Now let’s analyze the parameters provided to Cloudinary:</p><ul><li><strong>w_500</strong>: The image’s width must be 500px</li><li><strong>q_auto</strong>: Cloudinary can choose the optimal quality for the image</li><li><strong>f_auto</strong>: Cloudinary can choose the best format delivery for the image, for example, the image originally is a png but they can use a <a href="https://developers.google.com/speed/webp">webp</a> format which allows having a fewer quality loss</li></ul><p>I didn’t even know this image format existed before I built the landing page, and we don’t even know if new formats will appear in the future that optimizes compression way further, so it was nice to delegate this kind of job to a third party and just focus on building the website I want.</p><p>They come with a free plan that was good enough for my use case, I encourage you to visit their prices and services to see if it suits your needs.</p><p>Just by using Cloudinary, my lighthouse score improved quickly since the size of my thumbnails was like 5kb and full-size images like 60–100kb.</p><h4><strong>Optimizing icons</strong></h4><p>The next step was following <a href="https://vuetifyjs.com/en/features/icon-fonts/#material-design-icons---js-svg">Vuetify icon documentation</a> to avoid having to load all material design icons when I just needed like 10 of them.</p><p>Just to give you some insights, the @mdi/js package exports all icons as an SVG string, that way you can import the icons you need and use them in the rest of the page.</p><p>This is how I set up my icons to avoid having to import them into every component. Just declare your icons in a specific file and use them in the Vuetify instance options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*5Yv1x8GF3M1DmEIXXbcFDg.png" /></figure><p>The icons file should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5ZgwCDALFZhej48dx6oLg.png" /></figure><p>Then to use them in your Vuetify component you add the text $mdi-&lt;icon_name_in_kebab_case&gt; like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*ikIuPojFVI7sTyhwEYHHrA.png" /></figure><p>This way you don’t need to make drastic changes to your components in order to only import the ones you need.</p><h4>Font loading optimization</h4><p>There are several articles about this matter, this is the <a href="https://web.dev/defer-non-critical-css/">best one</a> I found, this StackOverflow question is also useful <a href="https://stackoverflow.com/questions/32759272/how-to-load-css-asynchronously">How to load CSS Asynchronously</a>. Lighthouse complained many times that I should preload the fonts CSS, then from the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content">official developer Mozilla docs</a> I got the following definition:</p><blockquote>The preload value of the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link">&lt;link&gt;</a> element&#39;s <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-rel">rel</a> attribute lets you declare fetch requests in the HTML&#39;s <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head">&lt;head&gt;</a>, specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers&#39; main rendering machinery kicks in. This ensures they are available earlier and are less likely to block the page&#39;s render, improving performance.</blockquote><p>There is another great article from a guy that actually performed all kinds of tests over font loading <a href="https://csswizardry.com/2020/05/the-fastest-google-fonts/">The Fastest Google Fonts</a>.</p><p>So I end up with the following font set up:</p><pre>&lt;!--<br>  - 1. Preemptively warm up the fonts’ origin.<br>  - 2. Initiate a high-priority, asynchronous fetch for the CSS file. Works in most modern browsers.<br>  - 3. Initiate a low-priority, asynchronous fetch that gets applied to the page only after it’s arrived. Works in all browsers with JavaScript enabled.</pre><pre>--&gt;<br>&lt;link <em>rel</em>=&quot;preconnect&quot; <em>href</em>=&quot;https://fonts.gstatic.com&quot; <em>crossorigin </em>/&gt;<br>&lt;link <em>rel</em>=&quot;preload&quot; <em>as</em>=&quot;style&quot; <em>href</em>=&quot;https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900&amp;display=swap&quot;&gt;<br>&lt;link <em>rel</em>=&quot;stylesheet&quot;<br>      <em>href</em>=&quot;https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900&amp;display=swap&quot;<br>      <em>as</em>=&quot;style&quot; <em>onload</em>=&quot;<em>this</em>.rel=&#39;stylesheet&#39;&quot; /&gt;</pre><p>With this lighthouse stop complaining about having blocking CSS that needed to be preloaded.</p><h4>UI Framework limitations</h4><p>Now it came the ugly part, getting a bad score in page speed insights about things I didn’t entirely control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UuPqYzUSz94SqoNoRy3zCw.png" /></figure><p>No matter what I did I kept having a 70–75 score from lighthouse for mobile devices, however, for desktop, I got nearly a perfect score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cVZflBryywBo4kMnIGYOxg.png" /></figure><p>I even ran the tests locally in an incognito window just to confirm and I got the same result, with no clue of what to do I look for issues related to Vuetify since it was the nearest abstraction layer, I already reviewed the benchmarks for Vue and it wasn’t the issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NUFaw1KIdi6yE-ykUBjPyg.png" /><figcaption>Lighthouse score locally for desktop</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ChcLvzmoFHi6iM6FhGNt_A.png" /><figcaption>Lighthouse score locally for mobile</figcaption></figure><p>I realized I wasn’t the only one having bad lighthouse scores and that this is a known issue for Vuetify <a href="https://github.com/vuetifyjs/vuetify/issues/7265">https://github.com/vuetifyjs/vuetify/issues/7265</a></p><p>Apparently, even by just creating a Vuetify app you couldn’t get a score above 80 which was a bummer, because there wasn’t a lot I could do to solve it, but then I remembered a quote from the Clean Code book from Robert C. Martin:</p><blockquote>Neither architecture nor clean code insist on perfection, only on honesty and doing the best we can. To err is human; to forgive, divine. […]. We air our dirty laundry. We are honest about the state of our code because code is never perfect. We become more fully human, more worthy of the divine, and closer to that greatness in the details.</blockquote><p>I really like Vuetify, and with version 3 coming out I hope they can improve the framework’s performance, I’m not going to lie I was disappointed to realize this, but I decided to keep optimistic and understand that code is something that’s constantly evolving with us and that this kind of issues are more common than I would like them to.</p><p>For example, I found a couple of articles about <a href="https://dev.to/gaelferrand/why-you-should-not-use-material-ui-21nn">Why you should NOT use Material-UI</a> a popular UI framework for React, or the problem of <a href="https://orkhanhuseyn.medium.com/ant-design-or-elephant-design-a03c19549553">Ant Design components being too heavy</a> I don’t know if these issues are recent or not, or even if we can compare it to my personal experience building this landing, what I do know is that being a Software Developer requires a lot of endurance, patience, and honesty about what’s the best you can do and to keep working to make things better, and that is something we all share.</p><p>I will keep looking for the best tools that help me build better apps, in the meantime I still like Vuetify and I will wait to see how version 3 will perform.</p><h4>Remove unused code</h4><p>I thought using <a href="https://bundlephobia.com/">bundlephobia</a> to analyze the final size of the library/package was enough to decide if it was worth it or not, but I forgot a valuable lesson, even when you deliver gzipped files you can have bad scores in lighthouse if you have unused javascript or CSS, why? <strong>Because gzipping only improves the network transference, the browser will still have to parse everything.</strong></p><p>For example, I decided to read the final generated CSS and I realized that even though Vuetify only adds CSS for the components I use, there are several global classes that I never used or some CSS really specific for some components states that I wasn’t going to need like several classes for <a href="https://en.wikipedia.org/wiki/Right-to-left_script">Right-to-left</a> script used for specific languages or classes for the light theme when I only used the dark theme.</p><p>Now tools like <a href="https://tailwindcss.com/">tailwindcss</a> make you think about how to optimize your components to strip everything that you don’t use for production, using tools like <a href="https://postcss.org/">PostCSS</a> helped me remove the mentioned CSS and I was able to remove about 100kb off the non-gzipped-generated CSS which initially weighted 418kb, which was a lot by just installing a tool and reading your production bundle.</p><p>I didn’t mess around with my final javascript bundle besides it being quite huge (407kb unzipped).</p><p>From this experience, I learned more about the real cost of dependencies and to be more aware during development to detect which are the bottleneck and what things to consider every time I need to pick a library or even if in some circumstances is better for your to write your own solution.</p><p>I will share my final post.config.js file for you to get an idea of how to strip classes from your final CSS.</p><pre><em>// postcss.config.js<br>const </em>IN_PRODUCTION = process.env.NODE_ENV === &quot;production&quot;;<br><em>const </em>margins = [&quot;ml&quot;, &quot;mr&quot;, &quot;mb&quot;, &quot;mt&quot;, &quot;mx&quot;, &quot;my&quot;, &quot;ma&quot;];<br><em>const </em>paddings = [&quot;pl&quot;, &quot;pr&quot;, &quot;pb&quot;, &quot;pt&quot;, &quot;px&quot;, &quot;py&quot;, &quot;pa&quot;];<br><em>const </em>sizes = [&quot;xs&quot;, &quot;sm&quot;, &quot;md&quot;, &quot;lg&quot;, &quot;xl&quot;];<br><em>const </em>CSS_SELECTORS_TO_REMOVE = [<br>  &quot;rtl&quot;,<br>  &quot;picker&quot;,<br>  &quot;theme--light&quot;,<br>  &quot;order&quot;,<br>  &quot;hidden&quot;,<br>  &quot;overflow&quot;,<br>  ...[paddings, ...margins]<br>    .map((item) =&gt; sizes.map((size) =&gt; `${item}-${size}`))<br>    .flat(),<br>];<br><br>module.exports = {<br>  plugins: [<br>    IN_PRODUCTION &amp;&amp;<br>      <em>// eslint-disable-next-line @typescript-eslint/no-var-requires<br>      </em>require(&quot;@fullhuman/postcss-purgecss&quot;)({<br>        content: [<br>          `./public/**/*.html`,<br>          `./src/**/*.vue`,<br>          `./node_modules/vuetify/dist/vuetify.css`,<br>        ],<br>        blocklist: CSS_SELECTORS_TO_REMOVE.map(<br>          (selector) =&gt; <em>new </em>RegExp(`.*${selector}.*`)<br>        ),<br>        safelist: [/^router-link(|-exact)-active$/, /data-v-.*/, /.*xyz.*/],<br>      }),<br>  ],<br>};</pre><h3>Conclusion</h3><p>I hope you have enjoyed and learned something from this article, building something always come with unexpected situations, in the end, we just need to keep learning from whatever we do, to be honest, and keep working to make things better and transform our realities since building Software is kinda like a superpower, use it wisely.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99db1ceeb0cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hasura GraphQL Practical Guide]]></title>
            <link>https://medium.com/plusteam/hasura-graphql-practical-guide-4fe438f2079a?source=rss-d1eb5173ac04------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fe438f2079a</guid>
            <category><![CDATA[hasura]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Julia Suarez]]></dc:creator>
            <pubDate>Thu, 22 Apr 2021 14:32:16 GMT</pubDate>
            <atom:updated>2021-04-22T14:32:16.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LTontYfBVugptsGBUo20w.png" /><figcaption>Hasura console</figcaption></figure><p>During this guide you will have a playground available to understand how to build and maintain a GraphQL API using Hasura, it’s recommended that you are familiar with what is GraphQL and its advantages over REST since this is a practical guide, you can learn the basics about GraphQL in this <a href="https://www.howtographql.com/">tutorial</a>.</p><p>The code is available in this <a href="https://github.com/JSilversun/hasura_tutorial">Github repository</a>.</p><h3>Technology Stack</h3><p>Before starting this tutorial, make sure you have installed and understand the basics of:</p><ol><li><strong>git</strong>: Code version management</li><li><strong>docker</strong>: Tool to build and manage containers</li><li><strong>docker-compose</strong>: Tool to manage several containers</li><li><strong>NodeJS and npm: </strong>Node is used only to set up Hasura actions and triggers.</li></ol><blockquote><strong>Note</strong>: To fully explore Hasura, some examples use a basic NodeJS server with express however this is just for demonstrating purposes and understanding NodeJS is NOT required.</blockquote><h3>Quick Start</h3><p>For this guide, I have prepared a playground repository with everything you need to fully test the tool and build your own GraphQL API from scratch. To avoid the overhead to set up a relational database with data and relationships, we will use an existing one called <a href="https://github.com/devrimgunduz/pagila">Pagila</a> a Postgres Database Sample taken from this <a href="https://data-xtractor.com/blog/data-modeling/example-databases/">great article</a> with a list of example databases, this database is about a DVD rental store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mmFj7406eFEmQLcm.png" /></figure><p>I recommend you to use a database explorer tool like DbBeaveror DataGripso you can take a better look at the database structure, however, <strong>it’s not important to understand everything</strong>, you just need to get familiar with it since we will query some data and change it.</p><blockquote><strong>Note</strong>: I wrote this tutorial so you can set up everything step by step, however, if for some reason you just want to run and test the final results, <a href="https://github.com/JSilversun/hasura_tutorial/blob/main/docs/run-final-api.md">this document</a> explains how to do it</blockquote><h3>Steps to set up the project</h3><ol><li>Clone the repository:<br>git clone <a href="https://github.com/jsilversun/hasura_tutorial">https://github.com/jsilversun/hasura_tutorial</a></li><li>Install the dependencies: <br>npm install</li><li>Clone the Pagila SQL scripts to the database folder<br> npm run database:clone</li><li>Run npx hasura init hasura-tutorial --admin-secret secret afterward, you will see a new folder named hasura-tutorial this will contain all the settings you need for your particular Hasura instance like metadata, actions, and migrations</li><li>Run docker-compose up -d to start the docker containers specified in the docker-compose.yml file</li></ol><blockquote><strong>Note</strong>: By running docker-compose down you can delete your containers and then run docker-compose up -d to start from scratch (This will reset both the API and the database).</blockquote><p>Then you will see the following file structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*zzUMkt_NAMa03s22YDau-A.png" /></figure><blockquote><strong>Note</strong>: If you are interested in understanding the project’s file structure, you can read this <a href="https://github.com/JSilversun/hasura_tutorial/blob/main/docs/file-structure.md">doc</a>.</blockquote><p>And you can see your running containers with the docker ps command, which confirms we have a GraphQL API running in the 8080 port and the database is using the 5432.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vgyxuzkzJU4ZvG_eoXty6w.png" /></figure><p>Now we can use the Hasura Console which is a graphical tool to explore or change settings in our new GraphQL API.</p><p>Run npx hasura console --project=hasura-tutorial</p><p>Then you will be redirected to <a href="http://localhost:9695/">http://localhost:9695/</a> and you will see how the Hasura Console looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EbHH6Ad1lxtPhmO8.png" /></figure><p>Now we are ready to start!</p><h3>Set up the GraphQL API</h3><ol><li>Go to the Data tab</li><li>Click on Track all tables</li><li>Click on Track all relations</li></ol><p>Now you have your own GraphQL API ready to go!</p><h3>Basics</h3><p>In this section we will learn the three main operations you can do over a GraphQL API. Go to the GraphiQL Tab.</p><h4><strong>Query</strong></h4><p>Remember to check <a href="https://hasura.io/docs/1.0/graphql/core/queries/index.html#">Hasura queries documentation</a> so you can learn more about the API, in this tutorial we will explore different examples but you can try your own examples from whatever you want to try in the database.</p><p>Queries are a simple way to get data from a backend, in this case, we can get information from the database by using Hasura.</p><p><strong>Get all available actors</strong></p><pre><em>query </em>getActors {<br>  actor {<br>    actor_id<br>    first_name<br>    last_name<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o7mgzyvyiIvR4gna.png" /></figure><p><strong>Get an actor by id</strong></p><pre><em>query </em>getActorById {<br>  actor_by_pk(actor_id: 1) {<br>    actor_id<br>    first_name<br>    last_name<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_d75YDJ0N3F_W9deGaEWA.png" /></figure><p><strong>Get an actor by id with his films</strong></p><pre>query getActors {<br>  actor_by_pk(actor_id: 1) {<br>    actor_id<br>    first_name<br>    last_name<br>    film_actors {<br>      film {<br>        film_id<br>        description<br>      }<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwmSjjDJOIoI7rbXkFTKbw.png" /></figure><p><strong>Get films with a replacement cost lower than 10</strong></p><pre>query getFilmsFrom {<br>  film(where: {replacement_cost: {_lt: 10}}) {<br>    film_id<br>    description<br>    replacement_cost<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HS0lr0F0uqHXlgxzlFgVEg.png" /></figure><h4><strong>Aggregation queries</strong></h4><p><strong>Get the average rental rate for films</strong></p><pre><em>query </em>{<br>  film_aggregate {<br>    aggregate {<br>      avg {<br>        rental_rate<br>      }<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6_S95L8TuQgbvNFA5fwpg.png" /></figure><h4><strong>Subscription</strong></h4><p><a href="https://hasura.io/docs/1.0/graphql/core/subscriptions/index.html">Hasura subscriptions documentation</a></p><blockquote>“A GraphQL subscription is essentially a query where the client receives an update whenever the value of any field changes upstream.</blockquote><blockquote>Subscriptions are supported for all kinds of queries. All the concepts of <a href="https://hasura.io/docs/1.0/graphql/core/queries/index.html#queries">queries</a> hold true for subscriptions as well.”</blockquote><p>Subscriptions are an incredible feature for automatic updates in the client, let’s see it in action.</p><p>Run the following GraphQL subscription:</p><pre><em>subscription </em>getActorById {<br>  actor_by_pk(actor_id: 1) {<br>    actor_id<br>    first_name<br>    last_name<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A7DygTmmZD5Y3IrTTObbnA.png" /></figure><p>You will see it&#39;s still running since it has a pause button, now open another Hasura console in a different browser tab, go to the Data section, look for the actor table click the editbutton and change the name of the actor from PENELOPE to PENELOPE!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SDKT_3sKmwHuhpO3.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-EVKZbyUQxCOGvTj.png" /></figure><p>Go back to your original tab and you will see how the result changed automatically</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zS28bgUUI6YgqAyli7WakA.png" /></figure><p>This amazing feature will allow the frontend clients to get automatic updates so your system will be refreshed in real-time, subscriptions apply to any Hasura query, test this feature further so you can see its capabilities.</p><p><strong>Mutation</strong></p><p>Let’s roll back the name of the actor we changed earlier in the subscription example from PENELOPE!to PENELOPE</p><pre><em>mutation </em>updateActorById {<br>  update_actor_by_pk(<br>    pk_columns: {<br>      actor_id: 1<br>    },<br>    _set: {<br>      first_name: &quot;PENELOPE&quot;<br>    }<br>  ) {<br>    actor_id<br>    first_name<br>    last_name<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2yhiqm8IRX1xTVnNlOA7Q.png" /></figure><p>Then if you refresh the actortable in the Data tab and you will see the record was updated successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yKA9MQ6DDxiICYwT.png" /></figure><h3>Authentication</h3><p>For authentication, we will explain how to use firebase to get a JSON Web Tokens (JWT) and then perform queries to the API, since I like practical examples I prepared two endpoints that you can use to get some JWT’s to use with Hasura.</p><blockquote><strong>Note</strong>: If you want to learn how these endpoints work and how you can run them locally please read <a href="https://github.com/JSilversun/hasura_tutorial/blob/main/docs/firebase-authentication.md">this doc</a>.</blockquote><p>For more information in <a href="https://jwt.io/introduction">this link you can read more about what JWT are</a>, in this guide we will focus on how to actually use them and see their content so we can build our secure API.</p><h3>Authentication</h3><ol><li>To get a JWT for the <strong>staff</strong> role visit the URL <a href="https://hasura-guide.herokuapp.com/staff">https://hasura-guide.herokuapp.com/staff</a> and copy the token</li><li>To get a JWT for the <strong>customer</strong> role visit the URL <a href="https://hasura-guide.herokuapp.com/customer">https://hasura-guide.herokuapp.com/customer</a> and copy the token</li><li>With each one of the tokens, go to the Hasura console</li><li>Add anAuthorization header and paste the token like this: Bearer &lt;pasted_token&gt;</li><li>Press the Decode JWT button shown in the screenshot below</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IeOn5IWOtE06YhhC.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9fm7zc0Cre6nS63V.png" /></figure><p>In the FULLY PAYLOAD DATA section you will see the entire JWT, in few words the entire token you copied from the page is nothing more than a JSON encrypted as a string and signed by firebase.</p><p>Authorization using JWT is just sending this token in the headers of any HTTP request, then Hasura will decode the JWT and get the user identifiers like the user id and email, which can be used to see if the user is authorized or not to do the requested operation, but first, how does Hasura know that he can trust the JWT received?</p><p>Well, it’s important to notice, Hasura receives an environment variable HASURA_GRAPHQL_JWT_SECRET this is another JSON used to set up the JWT authentication feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WB0f68cS2j-q6K2z.png" /><figcaption>Extract from the docker-compose.yml file to see how the HASURA_GRAPHQL_JWT_SECRET is passed to the GraphQL Engine</figcaption></figure><p>If we visit the <a href="https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com">URL</a> provided in the jwk_url property we will see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EAegEP5aAEAmL8lg.png" /></figure><p>I know this looks a bit confusing but this is just a JSON Web <strong>Key</strong>, it’s a public key that can be used to verify if a JWT has been signed using it. Hasura will perform an HTTP request to the jwk_url specified to get the public key(JWK) and then it will proceed to verify each JWT received to see if it has been signed with it, if the verification succeeds, then it means Hasura can trust the JWT content and then use the values to perform validations and see if the user is authorized or not.</p><p><a href="https://hasura.io/docs/1.0/graphql/core/auth/authentication/jwt.html">Hasura documentation about this subject</a> is great, it has all the information you need to know, in this guide I just want to give you the easiest example so you can test it on your own.</p><blockquote><strong>Note</strong>: Please notice in the jwk_url we are specifying the url where firebase publish their JWK used to sign the tokens, however you should specify the audience in the HASURA_GRAPHQL_JWT_SECRET to guarantee that only signed tokens by firebase for your <strong>specific application </strong>are considered valid otherwise any other JWT signed by firebase for other projects will be marked as valid for hasura and this is not safe, for the simplicity of the example this setting is omitted, make sure you <a href="https://hasura.io/docs/1.0/graphql/core/auth/authentication/jwt.html#audience">read hasura documentation</a> to understand this better.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9T-kxV5hizIEk8KM.png" /></figure><h3>Authorization</h3><p>Now we have two sample JWT that Hasura recognizes as valid, however, if we attempt to perform any query with them we will get an error because none of those roles are recognized by Hasura.</p><blockquote><strong>Note</strong>: You need to disable the x-hasura-admin-secret header so hasura will use the JWT to perform the authentication and authorization.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eYH8OqDDJ6n4oB5O.png" /></figure><p>Let’s allow customers to query their own information.</p><p>Go to the Data tab, look for the customer table and go to Permissions tab, enter the role customer in the “Enter new role” input and click on the pencil in the select section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6iG2pg5G7m2YSIBhbHP2A.png" /></figure><p>Now click the With custom check radio button and you will see a form that will help you build a JSON used to specify the permissions, however, you can just write the JSON on your own and then paste it in the small input above, paste the following JSON into the mentioned input.</p><pre>{<br>  &quot;_and&quot;: [<br>    {<br>      &quot;active&quot;: {<br>        &quot;_eq&quot;: 1<br>      }<br>    },<br>    {<br>      &quot;email&quot;: {<br>        &quot;_eq&quot;: &quot;X-Hasura-User-Email&quot;<br>      }<br>    }<br>  ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U244FsN_p1imjETh.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SkOCU_x0JXgV8olZ.png" /></figure><p>This JSON is saying: A user can see the record(s) in the customer table where the record’semail is the same as the one provided in the JWT and the record is active.</p><p>Also, we can specify which fields can be queried through Hasura, this way we can keep hidden internal fields like the active and activebool fields since it’s not useful to have them visible for the customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1-OebApSN4YEDXu2.png" /></figure><p>After you finish selecting the fields that will be visible, you can click on Save permissions.</p><p>Pretty simple but powerful. Now let’s test this, first, we need to change the email of one of the customers to customer@example.com since the Pagila database had different email examples.</p><p>Let’s change the email of the first customer from MARY.SMITH@sakilacustomer.org to customer@example.com</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dLth-J7hvhwA6VIt.png" /></figure><p>Then we go to the GraphiQL tab and perform the same query we did before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9_bL-JqYfyfaZT9u.png" /></figure><p>Notice how we are not using any filter operators and yet we only get one customer record because it matches the email from the JWT which we can trust since it was signed by firebase. If the customer table had the user id from firebase we would have been able to use it as well.</p><p>Now, let’s allow the customer to query their rental records. Go to the Data &gt; Rental &gt; Permissions then paste the following JSON in the same way we did before, select all the fields and afterward save the permissions.</p><pre>{<br>  &quot;customer&quot;: {<br>    &quot;email&quot;: {<br>      &quot;_eq&quot;: &quot;X-Hasura-User-Email&quot;<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nGX1cDM2JTrt4NBC.png" /></figure><p>Now we can perform a query like this one:</p><pre>{<br>  customer {<br>    customer_id<br>    email<br>    first_name<br>    last_name<br>    rentals {<br>      rental_date<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O1QFWKTvHbOib7eC.png" /></figure><p>And also you can query the rentals directly without having to query the customer first, the permissions will work anyway.</p><pre>{<br>  rental {<br>    customer_id<br>    rental_id<br>    rental_date<br>    return_date<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r-qR8AplnfHUoRFr.png" /></figure><p>You can even allow the user to perform aggregation queries by checking a field in the permissions tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x_OFMYM8iqkK1v4U.png" /></figure><p>Then we can perform aggregation queries like counting the total rentals for the authenticated user</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iFPB9WWR543LTFCm.png" /></figure><h3>Migrations</h3><p>Migrations are SQL instructions to indicate how the database structure and data can change over time without having to wipe the entire database to do so.</p><p>For example, I realized the activebool field in the table customer is not useful since all the records have a truevalue and there is an existing active field with values of 1 or 0 to indicate if the customer is active or not, to remove the unused field we can use the Hasura UI to remove the field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5EC8IIaH18Gpz-R8.png" /></figure><p>Then we will get this message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/0*ClbmcimCLPTaEABo.png" /></figure><p>So, a cool Hasura feature, is that you can use the Hasura console (Web UI) to modify the database structure and automatically generate migrations so the system will be modified automatically.</p><p>Let’s take a look at the migrations folder and we can see what was generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*OVZ7y9iczMyMoSEx.png" /></figure><p>We have our first migration!</p><p>Each migration is a folder with the timestamp as a prefix, this is used to guarantee migrations run in the order shown in the folder so they can mutate the database and the data with it.</p><p>The up.sql file just contains a SQL sentence to remove the column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wl11ss7FKS8lk8Or.png" /></figure><p>And the down.sql has the following SQL sentences to restore the field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*92vHJ68a1aO6EjfS.png" /></figure><p>So what can we do if we realize we need to roll back our system since it was a mistake to remove the activebool?</p><p>First, we can use the hasura cli to ask the migrations status by running at the hasura-tutorial folder:</p><p>npx hasura migrate status</p><p>And get something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Ut7Ntkvqkn7OHtj.png" /></figure><p>Now we can ask Hasura to roll back that migration by its version (The number in the migration folder we saw earlier).</p><p>hasura migrate apply --version 1611884791540 --type down</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lYze_I0wI70j06Vt.png" /></figure><p>If we go back to the Data tab we will notice the activebool field is back and since we had existing data, the value was set to NULL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4Ns_Ahxd_j2JSA9J.png" /></figure><p>We can modify the down migration so it can set the activebool field to true that way we can “travel in time” in the database structure, this example is just meant to teach you that you can modify the generated SQL’s as you please since it’s normal that you might want to perform more complex operations to the database that cannot be generated by using the Hasura UI automatically.</p><p>We will simplify the SQL sentence of the down migration like this:</p><pre><em>ALTER TABLE </em>&quot;public&quot;.&quot;customer&quot; <em>ADD COLUMN </em>&quot;activebool&quot; bool <em>DEFAULT true NOT NULL</em>;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZcafG2e6dxjdHB4v.png" /></figure><p>Then we can run the following sentences to remove the field again and to rollback one more time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SjAwQdANI9W-Qc6J.png" /></figure><p>If we refresh the Hasura console we will see the activebool field is back with true as the default value for all the records as it was initially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OEdQs5KNg1-3iIYG.png" /></figure><p>As a final tool about database migrations, what happens if you want to do any complex operation like adding a trigger or several updates to the database?</p><p>Well you can go to Data &gt; Migrations section and write some SQL change the default value of the activebool column to false</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_YYwuMP5jgAp9Ws6.png" /></figure><p>This will generate a new migration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*JAbbCS_KjofDryUm.png" /></figure><p>However, we can see it doesn’t have a down.sql file, it’s important we add one so it’s possible to roll back database changes whenever possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oXF859eESqRsC4OK.png" /></figure><p>Do the same process mentioned for the first migration to roll back and apply again the migrations to verify everything is working as expected.</p><h3>Metadata</h3><p>Hasura metadata is a data structure used to specify the GraphQL API settings like permissions per role or fields, Hasura defines it as:</p><blockquote>“All the actions performed on the console, like tracking tables/views/functions, creating relationships, configuring permissions, creating event triggers and remote schemas, etc. can be exported as a JSON/yaml metadata file which can be version controlled. The metadata file can be later imported to another Hasura instance to get the same configuration. You can also manually edit the metadata file to add more objects to it and then use it to update the instance.”</blockquote><p>This data structure is critical and understanding it will help you debug any problems when your API is unable to run due to inconsistent metadata.</p><p>As mentioned earlier, all settings are stored in the Hasura folder we created named hasura-tutorial in here we have a folder called metadata which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/0*oZpoJTrnVtbfBMfQ.png" /></figure><p>Hasura has many features, more than the ones we are covering in this tutorial, however as you go testing features I recommend you to get familiar with each structure so you can debug problems in case they occur. The main one is the tables.yaml:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*X9ArjPYLi4Of2BRO.png" /></figure><p>It’s actually a simple data structure once you get familiar with it. It defines all the tables available with their name, fields, relationships, and even permissions as we can see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*92gZQO8VmMiDoZS7.png" /></figure><p>In this section we can see how Hasura stores the information we saved in their UI in the first part of this tutorial, this specifically describes the select permissions over the customer table for the customer role.</p><p>Besides the data structure is simple and you can understand it by being familiar with yaml files, inconsistent metadata is a scenario that can happen when for example a field is removed from the database by using a migration but the field is still present in the metadata, if you restart your GraphQL container you will end up with your API not being able to run due to inconsistent metadata.</p><p>The first step is to always look for the logs to understand what might be causing the issue, and that if it’s a situation like I described earlier about some field that is no longer present, then you can update the metadata manually to fix the issue and then restart the container.</p><blockquote><strong>Tip</strong></blockquote><blockquote>You might use the command docker logs &lt;container_name&gt; to read its logs but I recommend using the dashboard for docker</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WH4_nwCQp_ZMXMmY.png" /></figure><p>There are other tools that can improve the development experience and help you debug any problems with metadata like <a href="https://www.portainer.io/">portainer</a>, choose the best for your use case.</p><p>As a final recommendation, make sure you do a <strong>code review</strong> over the metadata changes on your project, <strong>don’t treat these changes like something generated since this can break your GraphQL API</strong>.</p><h3>Actions</h3><p>Hasura is an amazing tool to generate an API that allows CRUD operations over a database, but what if we need some custom logic like using a payment gateway for the movie rental?</p><p>For these scenarios we can use actions to extend our existing Graphql API, in few words we can tell Hasura to register custom mutations and then act as a middleware between a REST endpoint and the final client. Let’s see this with an example.</p><p>Go to the Actions section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dVcBTlT1B13e9iqS.png" /></figure><p>And create a new one like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jd-_NoI3blJb7oyQ.png" /></figure><p>Click on Create</p><p>Go back to the project folder and run npm run server:startthis will start a basic NodeJS server with an endpoint to return a string like “Greetings, &lt;name&gt;! Have a nice day”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jUOuHpoeTEIu7mGb.png" /></figure><p>This is the sample code for both the Hasura trigger and Hasura action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/0*sN7rxZ1aGj9Qm11J.png" /></figure><h3>Triggers</h3><p>To finish this tutorial we will use Hasura triggers, which is a sure feature where a REST endpoint can be called when a change occurs in the database either an INSERT, UPDATE or DELETE.</p><p>Go to the Events tab and click on the Create button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_QnwU37oEzApAuCY.png" /></figure><p>Now, we will go and update the activebool field in the customer table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sHbvDMiZdG7ohO5D.png" /></figure><p>Now you can go to Events &gt; Processed Events tab and you can see the event was processed successfully.</p><p>You can see both the request and the response of the trigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8uC7j7wyK2O3HZTV.png" /></figure><p>This feature is useful to automate any action that must happen when something changes in the database, maybe like sending an email or notification, start background processing tasks, etc.</p><h3>Conclusion</h3><p>I hope this tutorial has been useful to you to learn how to quickly build a GraphQL API from an existing database and how to extend it with custom logic or background processing tasks, Hasura has many features that are not covered in this guide, and the best way you find out about them is for you to read the documentation and keep testing everything on your own.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fe438f2079a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plusteam/hasura-graphql-practical-guide-4fe438f2079a">Hasura GraphQL Practical Guide</a> was originally published in <a href="https://medium.com/plusteam">plusteam</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pytest beginners guide]]></title>
            <link>https://medium.com/plusteam/pytest-beginners-guide-9fb9451706bf?source=rss-d1eb5173ac04------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fb9451706bf</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[fixtures]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pytest]]></category>
            <dc:creator><![CDATA[Julia Suarez]]></dc:creator>
            <pubDate>Tue, 25 Jun 2019 14:38:37 GMT</pubDate>
            <atom:updated>2019-06-25T14:38:37.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVhuCXUXYwgV4LNr3mwHNg.png" /><figcaption>Powered by <a href="https://carbon.now.sh/">https://carbon.now.sh</a></figcaption></figure><h3>Introduction</h3><p>In this guide, you will learn how to get started with pytest. Before we start you should be already familiar with unitary tests and why they are important. The goal of this article is to show you how to set up pytest and why should you use it.</p><p>Now, let’s begin. Unit tests are pieces of code that allows you to test the smallest parts of your application like modules, classes, components, etc.</p><p>They must be concise and test one thing at the time, that’s why their name is unit tests. There are several frameworks that will help you write unit tests effortless. For Python, the most popular is pytest according to <a href="https://www.slant.co/topics/2621/~best-python-unit-testing-frameworks">Slant</a>.</p><h3>Before getting started</h3><p>For this tutorial I will assume you know the following, also I’ll be using Python 3.6.5:</p><ul><li>What is a <a href="https://en.wikipedia.org/wiki/Command-line_interface">CLI</a></li><li>How to create a virtual environment</li><li>Python basic syntax (Dictionary, arrays, etc)</li><li>How to install packages</li><li>How to create Python modules</li></ul><p>If you are okay with that, let’s go before you get bored of me first!</p><h3>Pytest basics</h3><p>Here is a summary of what will be cover in this basics guide:</p><ul><li>Setup instructions</li><li>Test discovery</li><li>Configuration files</li><li>Fixtures</li><li>Asserts</li><li>Markers</li></ul><h3>Setup instructions</h3><ul><li>Create a folder for your project</li><li>Create a virtual environment with python3</li></ul><pre>mkdir venv<br>python3 -m venv venv<br>source venv/bin/activate</pre><ul><li>Install pytest</li></ul><pre>pip install pytest</pre><ul><li>Create a Python module named example and Python file for your source code (Mine will be code.py)</li></ul><p>That’s all the setup we will need for now. You should have a directory like this:</p><pre>.<br>├── venv/<br>├── example<br>|   ├── __init__.py<br>|   └── code.py<br>├── tests<br>|   ├── __init__.py<br>|   └── test_code.py</pre><p>Let’s run a hello world test, create a function to check if a number is even:</p><pre># example/code.py</pre><pre>def is_even(number):<br>	return number % 2 == 0</pre><p>Now we create our first test with something like:</p><pre># tests/test_code.py<br>from example.code import is_even</pre><pre>def test_valid_even():<br>	assert is_even(2)</pre><p>And we run our test with:</p><pre>pytest tests/test_code.py</pre><p>And success! Our output will be something like:</p><pre>================================================================================= test session starts ==================================================================================</pre><pre>platform darwin -- Python 3.6.5, pytest-4.1.1, py-1.7.0, pluggy-0.8.1</pre><pre>rootdir: /Users/js/Code/pytest_example, inifile:</pre><pre>collected 1 item                                                                                                                                                                       </pre><pre>tests/test_code.py .                                                                                                                                                    [100%]<br></pre><pre>=============================================================================== 1 passed in 0.09 seconds ===============================================================================</pre><p>Note: You will see a . (dot) when a test pass, if it fails you will see an F.</p><p>But guess what? You didn’t need to specify the file. If you run pytest in your terminal, you will get the same output thanks to pytest test discovery convention.</p><h3>Test discovery</h3><p>This is the file naming conventions `pytest` uses to find the tests. Here is an extract from the <a href="https://docs.pytest.org/en/latest/goodpractices.html">documentation</a>:</p><blockquote><em>pytest implements the following standard test discovery:</em></blockquote><blockquote>- If no arguments are specified then collection starts from <a href="https://docs.pytest.org/en/latest/reference.html#confval-testpaths">testpaths</a> (if configured) or the current directory. Alternatively, command line arguments can be used in any combination of directories, file names or node ids.</blockquote><blockquote>- Recurse into directories, unless they match <a href="https://docs.pytest.org/en/latest/reference.html#confval-norecursedirs">norecursedirs</a>.</blockquote><blockquote>- In those directories, search for test_*.py or *_test.py files, imported by their <a href="https://docs.pytest.org/en/latest/goodpractices.html#test-package-name">test package name</a>.</blockquote><blockquote>- From those files, collect test items:<br>-test_ prefixed test functions or methods outside of class<br>-test_ prefixed test functions or methods inside Test prefixed test classes (without an __init__ method)</blockquote><p>In summary, it means that by default pytest will find all files which match the regex test_*.py or *_test.py. Inside those files, it will collect all functions with the prefix test_ and then execute them.</p><p>The testpaths option allows you to change the root tests directory.</p><h3>Configuration files</h3><p>You can specify the initial configuration for pytest using a pytest.ini file. In it, you can choose the tests directories, name pattern, etc.</p><p>There are several files that you can use to setup pytest. This is an extract of the <a href="https://docs.pytest.org/en/latest/goodpractices.html">docs</a>:</p><pre># first look for pytest.ini files<br>path/pytest.ini<br>path/setup.cfg  # must also contain [tool:pytest] section to match<br>path/tox.ini    # must also contain [pytest] section to match<br>pytest.ini<br>... # all the way down to the root<br><br># now look for setup.py<br>path/setup.py<br>setup.py<br>... # all the way down to the root</pre><p>It establishes which is the precedence of the configuration files. If your project has several of these files when you run pytestit will tell you which file is using.</p><pre>================================================================================= test session starts ==================================================================================<br>platform darwin -- Python 3.6.5, pytest-4.1.1, py-1.7.0, pluggy-0.8.1<br>rootdir: /Users/js/Code/pytest_example, inifile: pytest.ini<br>collected 1 item</pre><p>In this <a href="https://docs.pytest.org/en/latest/reference.html#ini-options-ref">docs</a> you can see all the options you can use on a configuration file.</p><p>So far you learned how to create a simple test, how test discovery works and how to customize pytest configuration with a setup file. Now let’s start with the main features of pytest!</p><h3>Pytest features</h3><p>In here we will cover enough to get you started writing real-world tests. This is the list of features we will cover:</p><ul><li>Asserts</li><li>Fixtures</li><li>Markers</li></ul><h3>Asserts</h3><p>In pytest the asserts are simple and self-explanatory. You use the assert keyword with some expression that must be valid. Otherwise, the test will fail. Here is how it looks like when a test fails. (This is another extract from pytest <a href="https://docs.pytest.org/en/latest/reference.html">docs</a>):</p><pre>=========================== test session starts ============================<br>platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y<br>rootdir: $REGENDOC_TMPDIR, inifile:<br>collected 1 item</pre><pre>test_assert2.py F                                                    [100%]</pre><pre>================================= FAILURES =================================<br>___________________________ test_set_comparison ____________________________</pre><pre>    def test_set_comparison():<br>        set1 = set(&quot;1308&quot;)<br>        set2 = set(&quot;8035&quot;)<br>&gt;       assert set1 == set2<br>E       AssertionError: assert {&#39;0&#39;, &#39;1&#39;, &#39;3&#39;, &#39;8&#39;} == {&#39;0&#39;, &#39;3&#39;, &#39;5&#39;, &#39;8&#39;}<br>E         Extra items in the left set:<br>E         &#39;1&#39;<br>E         Extra items in the right set:<br>E         &#39;5&#39;<br>E         Use -v to get the full diff</pre><pre>test_assert2.py:5: AssertionError<br>========================= 1 failed in 0.12 seconds =========================</pre><p>It will tell you exactly what is failing in your expression. For more information about the assert keyword, check the docs <a href="https://docs.pytest.org/en/latest/reference.html">here</a>.</p><h3>Fixtures</h3><p>We finally got to the main feature of pytest. I had a hard time understanding pytest fixtures at the beginning. I felt like everybody was talking about how great they were and nobody was explaining what the hell they actually are.</p><p>Fixtures are an example of <a href="https://en.wikipedia.org/wiki/Dependency_injection">dependency injection</a> (you can read it in pytest docs <a href="https://pybit.es/pytest-fixtures.html">here</a>). Their goal is to inject some calculated values/objects that can be reused on your tests. Here is an extract from pytest <a href="https://docs.pytest.org/en/latest/fixture.html">docs</a>:</p><blockquote><strong><em>Fixtures: a prime example of dependency injection</em></strong></blockquote><blockquote><em>Fixtures allow test functions to easily receive and work against specific pre-initialized application objects without having to care about import/setup/cleanup details. It’s a prime example of </em><a href="http://en.wikipedia.org/wiki/Dependency_injection"><em>dependency injection</em></a><em> where fixture functions take the role of the </em>injector<em> and test functions are the </em>consumers<em> of fixture objects.</em></blockquote><p>Fixtures are functions decorated with the pytest decorator @pytest.fixture. By convention, all fixtures should be declared on the conftest.py file on the root directory of every Python module detected by pytest. Remember, pytest only detects modules according to the testpaths defined on your ini file.</p><p>Here is a conftest.py example:</p><pre># tests/conftest.py<br>import pytest</pre><pre>@pytest.fixture<br>def even_number():<br>	return 2</pre><p>Now we can change our old test with something like:</p><pre># tests/test_code.py<br>from example.code import is_even</pre><pre>def test_valid_even(even_number):<br>   assert is_even(even_number)</pre><p>If you execute it again you will see the test passed. I hope you see the fixtures huge potential. You can create complex objects for particular tests and reuse them.</p><p>Pytest workflow looks something like this:</p><ul><li>Find and read a configuration file</li><li>Identify all declared fixtures on conftest.py files and collect them</li><li>Collect all tests that match the specified directories and pattern on the ini file</li><li>Before executing each test, pytest will check the test arguments to see if it matches any collected fixture. If it does, it will execute the fixture and use the returned value as the parameter with the fixture name</li><li>After all pytest executes all the fixtures and replaced their respective value, it will run the test.</li></ul><h4>Scopes</h4><p>By default pytest executes all fixtures once per function. This can be expensive if, for example, you request data from an API. Each test with that fixture name as a parameter will make an API request, slowing down your tests. In summary, be aware of the following:</p><p><em>Every time an argument of any test matches the name of a collected fixture, </em><em>pytest will execute the fixture and use the returned value as the parameter to the function</em>. EVEN IF THE PARAMETER IS NOT USED.</p><p>For these situations, we have the scope parameter. This parameter allows us to reuse a fixture instance between tests. The possible values of the scope parameter are: function, class, module, package or session.</p><p>In the pytest docs there is a great <a href="https://docs.pytest.org/en/latest/fixture.html">example</a> of an smtp connection object:</p><pre># content of conftest.py<br>import pytest<br>import smtplib</pre><pre>@pytest.fixture(scope=&quot;module&quot;)<br>def smtp_connection():<br>   return smtplib.SMTP(&quot;smtp.gmail.com&quot;, 587, timeout=5)</pre><p>In this example, we can reuse the smtp connection object between all the tests in the same Python module. Imagine we want to execute some code after the smtp_connection fixture&#39;s execution:</p><pre># content of conftest.py</pre><pre>import smtplib<br>import pytest</pre><pre>@pytest.fixture(scope=&quot;module&quot;)<br>def smtp_connection():<br>   smtp_connection = smtplib.SMTP(&quot;smtp.gmail.com&quot;, 587, timeout=5)<br>   yield smtp_connection  # provide the fixture value<br>   print(&quot;teardown smtp&quot;)<br>   smtp_connection.close()</pre><p>Before we move to another pytest feature, I want to clarify that you can have several conftest.py files. You can have one conftest.py file per Python module detected by pytest, look at this example:</p><pre>.<br>├── tests<br>│  ├── __init__.py<br>│  ├── test_example.py<br>│  ├── conftest.py<br>│  └── api<br>│     ├── __init__.py<br>│     ├── test_api.py<br>│        └── conftest.py</pre><p>Notes: Tests defined in the test_example.py can use the fixtures defined in tests/conftest.py, but the test_api.py can use all fixtures from tests/conftest.py and tests/api/conftest.py.</p><h3>Markers</h3><p>Markers are a pytest decorator that allows you to classify your tests or perform some specific action.</p><p>To list all the markers you have defined execute:</p><pre>pytest --markers</pre><p>You will have an output with default markers, here you can see a summary of the most relevant ones:</p><pre>@pytest.mark.filterwarnings(warning): add a warning filter to the given test...</pre><pre>@pytest.mark.skip(reason=None): skip the given test function with an optional reason...</pre><pre>@pytest.mark.xfail(condition, reason=None, run=True, raises=None, strict=False): mark the test function as an expected failure if eval(condition) has a True value...</pre><pre>@pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in different arguments in turn. argvalues generally needs to be a list of values if argnames specifies only one name or a list of tuples of values if argnames specifies multiple names.</pre><p>The description is pretty much self-explanatory but let’s see some examples:</p><ul><li>@pytest.mark.skip(reason=None): With this marker pytest will skip the test, you can add a reason to explain why.</li></ul><pre>@pytest.mark.skip(reason=&#39;This test is no longer required&#39;)<br><br>  def test_valid_even(even_number):<br>      ...</pre><p>Also, there is a variation from this marker to skip the test if a condition is True: @pytest.mark.skipif(condition)</p><ul><li>@pytest.mark.xfail(condition, reason=None, run=True, raises=None, strict=False): With this, you can mark the test as Expected to fail if the condition parameter is True. This is useful if you write a test with a feature that hasn’t been implemented or when the functionality you were testing has changed and you know the test will fail.</li></ul><pre>@pytest.mark.xfail(reason=&#39;The is_even method functionality has changed&#39;)<br><br>  def test_valid_even(even_number):<br>      ...</pre><ul><li>@pytest.mark.parametrize(argnames, argvalues): This marker will allow you to reuse a test with different parameters so you include more cases or situations as input for your test.</li></ul><pre>@pytest.mark.parametrize(&quot;number&quot;, [2, 4, 6, 8])<br><br>  def test_valid_even(number):<br>      assert is_even(number)</pre><p>If you execute this, you will see that 4 tests pass because of each input count as an independent test</p><p>Here is a summary of the tests with markers and some distinct syntax you can use:</p><pre># tests/test_shopping_cart.py</pre><pre>import pytest</pre><pre>from cart.shopping_cart import is_even</pre><pre>@pytest.mark.skip(reason=&#39;This test is no longer needed&#39;)</pre><pre>def test_skip_example(even_number):<br>   assert is_even(even_number)</pre><pre>@pytest.mark.xfail(reason=&#39;An even number plus 1 will never be even&#39;)<br>def test_xfail_example(even_number):<br>   assert is_even(even_number + 1)</pre><pre>@pytest.mark.xfail(reason=&#39;This test will pass but its marked as expected to fail&#39;)</pre><pre>def test_xpass_example(even_number):<br>   assert is_even(even_number)</pre><pre>@pytest.mark.parametrize(&#39;even&#39;, [2, 4, 6, 8])<br>@pytest.mark.parametrize(&#39;not_even&#39;, [3, 5, 7, 9])<br>def test_parametrize_example1(even, not_even):<br>   assert is_even(even)<br>   assert not is_even(not_even)</pre><pre>@pytest.mark.parametrize(&#39;even, not_even&#39;, [(2, 3), (4, 5), (6, 7)])</pre><pre>def test_parametrize_example2(even, not_even):<br>   assert is_even(even)<br>   assert not is_even(not_even)</pre><pre># You can mark an individual test instance as expected to fail</pre><pre>@pytest.mark.parametrize(&#39;even, not_even&#39;, [(2, 3), pytest.param(5, 5, marks=pytest.mark.xfail)])</pre><pre>def test_parametrize_example3(even, not_even):<br>   assert is_even(even)<br>   assert not is_even(not_even)</pre><p>If you run all these tests, the output would be like:</p><pre>================================================================================= test session starts ==================================================================================</pre><pre>platform darwin -- Python 3.6.5, pytest-4.1.1, py-1.7.0, pluggy-0.8.1</pre><pre>rootdir: /Users/js/Code/pytest_example, inifile:</pre><pre>collected 24 items                                                                                                                                                                     </pre><pre>tests/test_shopping_cart.py sxX....................x                                                                                                                             [100%]</pre><pre>============================================================== 20 passed, 1 skipped, 2 xfailed, 1 xpassed in 0.14 seconds ==============================================================</pre><p><strong>Notes</strong>:</p><ul><li>All expected to fail tests that actually fail will show a lowercase x. In the other hand, if the test has the xfail marker but it passes, it will count as Unexpected passes. In the result, they will appear with an uppercase X.</li><li>pytest marks the skipped test with an s.</li><li>If you use the parametrize marker, pytest will run an independent test for each combination of parameters. You can mark a specific instance as Expected to fail.</li><li>If you want to see the reason for each marked test, you can add the -r flag, this is the description from the CLI help:</li></ul><pre>show extra test summary info as specified by chars (f)ailed, (E)error, (s)skipped, (x)failed, (X)passed, (p)passed, (P)passed with output, (a)all except pP. Warnings are displayed at all times except when --disable-warnings is set</pre><ul><li>For example, you can use this to get the extra summary for all cases:</li></ul><pre>pytest -ra</pre><h3>Some final tips</h3><p>If you have a lot of tests and need some kind of report, I would recommend you to try the Python package pytest-html. You can use it with the following command:</p><pre>pytest --html=report.html</pre><p>You will get something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C3TI264vSjbiepeb.png" /></figure><p>It can be useful if you have tons of tests. Also, if you use PyCharm as your code editor, use pytest scripts instead of Python scripts. The whole UI is completely different and you can see the results categorized per module and test.</p><p>Be aware of using fixtures which value isn’t actually used. Because they will be dead time, making your tests slower.</p><p>If you can, avoid making calls to external API, this is another huge factor that can make your tests REALLY slow. Consider using Mocking. I didn’t cover it on this guide, but it’s a good practice that helps you keep your test concise and small. Remember, is important to test one functionality at the time. Sometimes our units of code have a lot of logic within like a backend endpoint. For those cases try using several unit tests instead of a big one. Or consider using other types of tests like <a href="https://en.wikipedia.org/wiki/Integration_testing">Integration Tests</a>.</p><p>For a small introduction to Mocking, check this great <a href="https://medium.com/@piraveenaparalogarajah/what-is-mocking-in-testing-d4b0f2dbe20a">article</a>.</p><p>I hope this article was useful to you. I tried to include all the small things about pytest that took me a while to understand. Now go and write some awesome unitary tests with pytest!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fb9451706bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plusteam/pytest-beginners-guide-9fb9451706bf">Pytest beginners guide</a> was originally published in <a href="https://medium.com/plusteam">plusteam</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>