<?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 Chamara Madhushan Liyanage on Medium]]></title>
        <description><![CDATA[Stories by Chamara Madhushan Liyanage on Medium]]></description>
        <link>https://medium.com/@chamaral?source=rss-7b87a501d85b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2MLfmHnKFv5V8P3u40c5Qg.png</url>
            <title>Stories by Chamara Madhushan Liyanage on Medium</title>
            <link>https://medium.com/@chamaral?source=rss-7b87a501d85b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:06:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chamaral/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[My POV On Luck]]></title>
            <link>https://medium.com/@chamaral/my-pov-on-luck-b42ef41be780?source=rss-7b87a501d85b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b42ef41be780</guid>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[luck]]></category>
            <category><![CDATA[think]]></category>
            <dc:creator><![CDATA[Chamara Madhushan Liyanage]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 15:39:49 GMT</pubDate>
            <atom:updated>2024-10-19T15:39:49.709Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This article is not structured, I type what I think in random order.</p><ul><li>We are born with a magnet installed</li><li>This magnet can attract luck</li><li>This magnet can be either strong, meh, or weak</li><li>Luck is a fully random event fallen from the sky? May be maybe not, let’s see how it goes below<br>- Extremely lucky people<br>- Somewhat lucky people<br>- Unlucky people</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rlPx_H5exszf-Ds4XlXSg.jpeg" /></figure><ul><li>This is so sad if you fall under the last two categories</li><li>Extremely lucky people,<br>- Always get a good parking spot as soon they arrive at the supermarket (I drive in circles to get a spot near the entrance), they can be at the right place at the right time consistently. 😐</li><li>Others,<br>- They have to keep on searching and working hard to get an okay reward.</li><li>Is this familiar to you too? Have you thought that this is unfair? So I intend to avoid thinking about people in such a way.</li><li>So, let’s change how we think about luck, I came across a few great views on the internet and want to share the same with you, with my spice on it.</li></ul><h3>The idea is to create our luck.</h3><p>To achieve this we have to change our tactics a little bit and increase something called luck surface area. (LAS)</p><h3>What is Luck Surface Area</h3><ul><li>To understand this, think luck is happening at random</li><li>But, if you can position yourself in a way to capture most of it we win (we create our luck)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9FMC5z1CagqGRh1Wv6LuQ.jpeg" /></figure><ul><li>So, according to this luck is happening randomly but we have a way to capture most of it. In other words to make our luck magnet stronger.</li><li>This might not be easy at first but worth trying.</li><li>We have to practice what is called Doing and Telling<br>- Doing: Do more things<br>- Telling: Tell more people about what you are doing</li><li>As an example,<br> <strong>Doing</strong>: if you are interested in cycling. Buy a beginner mountain bike and ride it and most of all enjoy the ride, enjoy the outside world.</li><li><strong>Telling</strong>: This is important, while you are riding think about recording it. Post it on social media. First, no one will notice it.<br><strong><em>Do more:</em></strong> Search how to promote the content, and learn it so later you tell people about it too. Eventually, people might notice who you are. And you might feel this rewarding, They might reach out to you.<br><strong><em>Do more:</em></strong> Try to enhance the content quality, keep on improving and who knows bike sponsorships might reach out to you. Sportswear companies might reach out to you. This way you have created your luck.</li><li>This might be a hypothetical example, but think about it, there are things we can do and tell these days due to the maturity of the internet. Let’s make use of it.</li></ul><h3>Remember this</h3><blockquote>Luck = Doing things * Telling people</blockquote><p>But you may be reluctant at first to tell people about what you are doing there is a world that might be benefited from your outcome. So, get motivated.</p><p>There are a lot of things I did and never talked about. I mean not about murders and all. About good things. I never documented, I never posted, But one time I wrote a technical article about a very basic thing, which I thought that no one would worry about reading, it was that simple and basic. But you know what I recently noticed that over 100K people have read that article. So in one way, I’m happy because it was rewarding and on the other hand telling helps people. (be mindful about what you are telling though)</p><h3>Takeaways</h3><ul><li>It’s good to think that luck can be created rather than inherited</li><li>Create your luck by doing and telling</li><li>Improve qualities like<br>- Observing things around you<br>- Personal branding<br>- Networking<br>- Starting something at a small scale and growing, then tell about it (the Great Wall of China was not built overnight)</li><li>Overall you ̶m̶i̶g̶h̶t̶ will create your luck</li><li>So, good luck guys 😄 (See how I made a joke)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b42ef41be780" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is API Design First Approach — [Draft]]]></title>
            <link>https://medium.com/@chamaral/what-is-api-design-first-approach-draft-ee14ae1369c4?source=rss-7b87a501d85b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee14ae1369c4</guid>
            <category><![CDATA[openapi-generator]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Chamara Madhushan Liyanage]]></dc:creator>
            <pubDate>Tue, 11 Jan 2022 05:21:57 GMT</pubDate>
            <atom:updated>2022-01-19T04:53:52.028Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is API Design First Approach</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIVMjY0svmA8bC71xuN2Gg.png" /></figure><h3>Overview</h3><p>The Code First approach is a more traditional approach to building APIs, with the development of code happening after the business requirements are laid out, eventually generating the documentation from the code. The Design First approach advocates for designing the API’s contract first before writing any code.</p><p>The concept of the API starts with the business team identifying an opportunity. The opportunity is analyzed and a plan to capitalize on it is created in a text document by strategists, analysts, and other business folks. This document is then passed along to the development team, where the development of the API happens in two main ways</p><ol><li><strong>Design First:</strong> The plan is converted to a human and machine-readable contract, such as an <a href="https://swagger.io/specification/">OpenAPI specification document</a>, (Swagger document) from which the code is built</li><li><strong>Code First: </strong>Based on the business plan, API is directly coded, from which a human or machine-readable document, such as a Swagger document can be generated</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*S-fvxCa0YFtSoqpmOH7QZA.png" /><figcaption><a href="https://swagger.io/blog/api-design/design-first-or-code-first-api-development/">https://swagger.io/blog/api-design/design-first-or-code-first-api-development/</a></figcaption></figure><h3>Design first approach over code first approach</h3><ul><li>The biggest reason to go for the Design First approach is when your API’s target audience is external customers or partners. The API contract or the OpenAPI specification can be visualized with tools like Swagger UI which depicts the inputs and outputs in a more human-readable manner.</li><li>The API contract can act as the central draft that keeps all the team members aligned on what the API’s objectives are, and how the API’s resources are exposed. It’s easier for teams to reduce any mismatches between the integrations.</li><li>Sometimes with open-source tools, it’s possible to auto-generate stub codes against the OpenApi specification document with a considerable amount of initial code wiring which can boost the time to market.</li></ul><h3>Design philosophy</h3><p>There are 2 main opensource libraries that can be utilized to create the server stubs from the OpenAPI spec (2.0 and 3.0).</p><ul><li><a href="https://github.com/OpenAPITools/openapi-generator">GitHub - OpenAPITools/openapi-generator: OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)</a></li><li><a href="https://github.com/swagger-api/swagger-codegen">GitHub - swagger-api/swagger-codegen: swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.</a></li></ul><h3>Proceeding with openapi-generator</h3><p>In terms of capabilities, both of the libraries are the same, in fact, most of the base code is equal. However, the open API generator is more active and driven by the community and is documented ahead of the swagger-codegen.</p><blockquote>Swagger Codegen is driven by SmartBear while OpenAPI Generator is driven by the community. More than 40 top contributors and template creators of Swagger Codegen have joined OpenAPI Generator as the founding team members. For more details, see the <a href="https://openapi-generator.tech/docs/fork-qna">Fork Q&amp;A</a>. Read more <a href="https://openapi-generator.tech/docs/faq/">here</a>.</blockquote><h3>The integration</h3><p>There’s a plethora of <a href="https://github.com/OpenAPITools/openapi-generator#overview">languages and frameworks</a> supported by the OpenAPI Tool and however it misses the spring Gradle-based stub generation. It offered a maven-based implementation only. So, there are some amendments done in the initial integration to cater to this and bring support to the Gradle-based spring-boot applications.</p><p>The integration is done through org.openapi.generator Gradle plugin with the intention of generating the controllers(API) and dto(models) automatically against the provided OpenAPI specification document.</p><h3>The implementation</h3><p>The boilerplate code can be found here <a href="https://github.com/Gonzalliz/api-design-first-template">https://github.com/Gonzalliz/api-design-first-template</a>. Follow the README to run the application locally.</p><p>Changes and suggestions are welcome !!</p><h4>Points to consider</h4><ul><li>Auto-generated stubs by openapi-generator library follow code standards constrained by the library creators</li><li>The openapi-generator library and its dependencies work for spring-boot version 2.5.4 but not for the latest 2.6.2 as of Jan 10, 2022, hopefully, openapi-generator associated springfox-swagger2 and springfox-swagger-ui libraries will be made compatible with the latest spring-boot versions.</li></ul><h3>Reference</h3><ul><li><a href="https://swagger.io/blog/api-design/design-first-or-code-first-api-development/">https://swagger.io/blog/api-design/design-first-or-code-first-api-development/</a></li><li><a href="https://openapi-generator.tech/docs/faq/">https://openapi-generator.tech/docs/faq/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee14ae1369c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your Ubuntu OS more effective for programming and office work]]></title>
            <link>https://medium.com/hackernoon/make-your-ubuntu-os-more-effective-for-programming-and-office-work-2f07f3f21490?source=rss-7b87a501d85b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f07f3f21490</guid>
            <category><![CDATA[joplin]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[gnome]]></category>
            <category><![CDATA[wfh]]></category>
            <category><![CDATA[zsh]]></category>
            <dc:creator><![CDATA[Chamara Madhushan Liyanage]]></dc:creator>
            <pubDate>Sun, 19 Dec 2021 02:33:16 GMT</pubDate>
            <atom:updated>2021-12-20T02:30:23.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UfJO88RqQPpqysao.gif" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.nytimes.com%2F2018%2F06%2F26%2Fsmarter-living%2Fhow-to-clean-your-filthy-disgusting-laptop.html&amp;psig=AOvVaw0l4x3OfumUnjZZaY9pmtCM&amp;ust=1640053091838000&amp;source=images&amp;cd=vfe&amp;ved=0CAsQjRxqFwoTCJiZnY6o8fQCFQAAAAAdAAAAABAJ">source</a></figcaption></figure><h4>Background</h4><p>As programmers, we are keen on customizing and tweaking our OS a little bit to make it more effective and programmer-friendly. Here’s how I accomplished some undersized mods to my office laptop which is running on Ubuntu 20.04 LTS.</p><p>By default macOS and Linux is a bit programmer-friendly in my sentiment and by nature, any Linux variant is highly customizable than macOS. So let’s see how I turned my laptop more effective for office work.</p><h4>Install `build-essential` package in Ubuntu</h4><pre>sudo apt update<br>sudo apt install build-essential</pre><p>Well, all might not need this however it contains a list of packages that are required to create a Debian package (deb). These packages are libc, gcc, g++, make, dpkg-dev etc.</p><p>There might be some usecases where you would install this before installing anything else. Let’s say f you have to use an unusual software that is only available from the source code, your system will throw <strong>make</strong> command not found error because you need to install <strong>make</strong> tool first. And some tools might use <strong>g++</strong> compiler and you can install these individually but it’s rather easy to quickly install this bundle to overcome a lot of hurdles.</p><h4>Install terminator</h4><p>I find the default terminal application bit tiresome, so recommend using terminator.</p><p>Refer to <a href="https://github.com/gnome-terminator/terminator">this</a> for installation</p><p>Some cool features include</p><ul><li>Arrange terminals in a grid.</li><li>Tabs.</li><li>Drag and drop re-ordering of terminals.</li><li>Lots of keyboard shortcuts (my favorite is splitting the terminals vertically or horizontally).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*M_R-XXwH5DI-fKk1pi8kDg.png" /></figure><h4>Use Zsh and install Oh My Zsh</h4><p>Bash is probably the most well-known shell we’ve used, but there are other widely-used options as well, such as <em>Zsh. </em><a href="https://github.com/ohmyzsh/ohmyzsh">Zsh</a>, also known as the Z shell, extends the functionality of the Bourne Shell (sh), offering newer features and more support for plugins and themes.</p><ul><li>Install zsh refer to <a href="https://github.com/ohmyzsh/ohmyzsh/wiki/Installing-ZSH">this</a> (explore a lot of tricks and tips of <strong>zsh</strong>)</li></ul><p>ex: <strong>take</strong>command will create a directory and navigate into it (eliminating the need to type the two commands <strong>mkdir</strong> and <strong>cd</strong>), The recursive search is more helpful and easy than in <strong>sh</strong> or <strong>bash</strong></p><ul><li>Install oh-my-zsh which is to manage zsh configurations. It provides a plethora of plugins. Refer to <a href="https://github.com/ohmyzsh/ohmyzsh">this</a></li></ul><p>What I use most is the <strong>git</strong> plugin and some themes which make my terminal looks nicer. The <strong>git</strong> plugin is really convenient for devs to know about the branching details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*azzXFDWwZuqWHvNz.png" /><figcaption>source: <a href="https://github.com/ohmyzsh/ohmyzsh">https://github.com/ohmyzsh/ohmyzsh</a></figcaption></figure><h4>Install ubuntu tweak tool</h4><pre>sudo apt install gnome-tweak-tool</pre><p>If you get an error in this installation I think you might need <strong>universe</strong> repository enabled on our Ubuntu system. Refer to <a href="https://linuxconfig.org/how-to-install-tweak-tool-on-ubuntu-20-04-lts-focal-fossa-linux">this</a>.</p><p>This gnome tweak tool can be used to adjust a lot of things in the system in an easy way.</p><h4>Customize the ubuntu Topbar (date-time, battery) using the gnome tweak tool</h4><p>Open the gnome tweak tool and customize the Topbar as you wish. I needed all the following details at a glance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eDX0_QO9YhHizwfNtnOd3w.png" /></figure><h4>Change the placement of title bar buttons</h4><p>Hmm, it’s totally up to you. I prefer right 😄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*IxLNOCQ3es1sFWH13Luw_Q.png" /></figure><h4>Enable ubuntu extensions</h4><p>Through extensions, we can extend some functionalities. I use the System monitor extension which I’ll be showing below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*sJgyHZKx6qZ5P8cWoecXQQ.png" /></figure><h4>Install System-monitor extension</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aVJK7vMCm68ky3fZkP4yg.png" /></figure><p>I needed to sometimes keep tabs on my CPU and Memory utilization during some program executions. Also sometimes I experienced slowness and performance issues when the memory utilization reaches 100% due to endless chrome tabs we open and never close as programmers 😆. So it’s handy to know how many resources are available. You can find a lot of customizability with this extension so explore.</p><p>Refer to <a href="https://github.com/paradoxxxzero/gnome-shell-system-monitor-applet">this</a> for installation</p><h4>Add the international clock (Gnome clock) 🕐</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*m8sxpX7Y3hcokziQtqBNPw.png" /></figure><p>Well, sometimes we need to work collaboratively with other developers who are in different time zones. In this case, it’s convenient if we can quickly see the time in other countries. So I got this feature by installing the Gnome clock. Refer to <a href="https://github.com/GNOME/gnome-clocks">this</a> for more.</p><pre>sudo apt install gnome-clocks</pre><p>Search for the installed gnome clock app and add the countries accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*tIz1WsRGt4xqUd5wkajY0Q.png" /></figure><h4>View holidays in the ubuntu calendar 📆</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*rc-96loCK7lng7bAP4woCQ.png" /></figure><p>It’s useful for me to quickly view upcoming holidays with the Ubuntu calendar panel if there’s a way. So I search through the internet and found out that integrating Google calendar to the Ubuntu calendar application kinda making it possible. So the result is above. Tiny dots below the calendar date is quite helpful to me sometimes in planning some of the sprint works considering both my local team and international teams. So I configured my google calendar to display both my country holidays and US holidays.</p><p>To enable this integrate google calendar to your Ubuntu calendar by going into Ubuntu settings → online accounts. Then only allow calendar permissions accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXE4JoGvtZqiPR44zI3xPA.png" /></figure><h4>Enable [preview + minimize] applications in taskbar button click action</h4><p>By default in Ubuntu, we can’t see all the open windows/applications at a glance using the taskbar buttons. Sometimes I need to switch between different windows of the same app without hitting Alt+Tab and cycling through all.</p><p>ex: IDEs, Web browser, etc.</p><p>So found this <strong>gsetting</strong> very helpful. Execute this command in the terminal</p><pre>gsettings set org.gnome.shell.extensions.dash-to-dock click-action ‘minimize-or-previews’</pre><h4>Use Jopline 📓</h4><p>It’s the note taking app I’m using as an alternative for Microsoft OneNote or Evernote <em>(which are not available for Linux other than web applications at the time of writing this article)</em>. I needed to have a convenient way to keep all the notes into different sections and categories and sync them to the cloud as well. There’s a mobile app too so you can jot down notes from anywhere. It supports markdown too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oc6b6YRLgBbiIrA1oK32vw.png" /></figure><p>Refer to <a href="https://joplinapp.org/help/#desktop-applications">this</a> for installation. (I think it needs <a href="https://nodejs.org/en/download/package-manager/">Node.js</a> ) 😅</p><h4>Use shutter 📷</h4><p>The default Ubuntu screenshot taking app is boring. 😕. So I use <a href="https://shutter-project.org/">shutter</a>. It’s easy to use and equipped with a handful of features. As devs we need to quickly capture a portion of the screen, edit (highlight, censor, crop) copy(ctrl+c), and paste to a chat right.</p><p>All the images above are easily captured and edited using the shutter itself. Below ones are too 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20MsxOFw6J01GM2YCRoGKA.png" /></figure><h4>Use Safe Eyes 👀</h4><p>This app is an open-source tool for Linux users to reduce and prevent repetitive strain injury (RSI).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*1BeT4hkZENVM18oxhitt8w.png" /></figure><p>Refer to <a href="https://slgobinath.github.io/SafeEyes/">this</a></p><h4>Miscellaneous</h4><p>Other than these things I always try to make the IDEs more customizable with themes and quick shortcuts so it’s totally up to you to decide your preference.</p><p>I use <a href="https://github.com/tonsky/FiraCode">FiraCode</a> font in all of my IDEs and Text editors including the terminal I guess. I find it more developer-friendly, again there are a bunch of good fonts out there so check them out too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*cgJU3X16TCIWjSRrRel6Vw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f07f3f21490" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/make-your-ubuntu-os-more-effective-for-programming-and-office-work-2f07f3f21490">Make your Ubuntu OS more effective for programming and office work</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My challenge of porting a production distributed agent software from Python 2.x to Python 3.x]]></title>
            <link>https://medium.com/@chamaral/my-challenge-of-porting-a-production-distributed-agent-software-from-python-2-x-to-python-3-x-3d31354c67d4?source=rss-7b87a501d85b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d31354c67d4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Chamara Madhushan Liyanage]]></dc:creator>
            <pubDate>Sun, 22 Mar 2020 09:15:14 GMT</pubDate>
            <atom:updated>2020-03-22T09:15:14.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nuog7HLL7V0k09Bvh0tXcQ.png" /></figure><h3>Base story</h3><p>The challenge was to fully convert the code base of an autonomous agent software which runs on Ubuntu OS. This agent is initially written in Python 2.7 and runs in over 10,000+ remote devices which runs on either Ubuntu 14.04 or 18.04.</p><h3>Why we need this ???</h3><p>Since Python 2 is getting deprecated and community support will eventually be dropped and as the production codebases should not contain deprecated technologies we took the decision of this migration.</p><h3>Challenges</h3><ol><li>Find the best suitable way to convert the whole codebase to Python 3</li><li>Thoroughly test the agent in all aspects and make sure this migration doesn’t introduce bugs and anomalous behaviors. (Criticality is that if I mess this, all these 10,000+ devices will be unreachable. (Think it like you sent an autonomous spaceship and you lost all the communications and lost the connection to Earth))</li><li>Finding how to upgrade these agents in 10,000+ remote devices smoothly without hindering customers&#39; production work.</li></ol><p>Since this is a bit longer I’ll divide this into 2 series.</p><p>Series 1: <a href="https://medium.com/@chamaral/converting-process-of-python-2-project-to-python-3-6119cbafba26">How to convert a codebase from Python 2 to Python 3</a></p><p>Series 2: <a href="https://medium.com/@chamaral/how-the-python-3-upgrade-happened-remotely-to-all-those-ubuntu-devices-ab160809046b">How the upgrade happened remotely to all those Ubuntu devices</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d31354c67d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting process of Python 2 project to Python 3]]></title>
            <link>https://medium.com/hackernoon/converting-process-of-python-2-project-to-python-3-6119cbafba26?source=rss-7b87a501d85b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6119cbafba26</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Chamara Madhushan Liyanage]]></dc:creator>
            <pubDate>Sun, 22 Mar 2020 09:12:38 GMT</pubDate>
            <atom:updated>2020-03-22T09:27:33.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmznGm2XEy92dPzhjzzXZw.png" /></figure><p>You can start reading on this but to know about my base story refer to <a href="https://medium.com/@chamaral/my-challenge-of-porting-a-production-distributed-agent-software-from-python-2-x-to-python-3-x-3d31354c67d4">this</a>.</p><p>There are a few things you need to know before jumping straight to conversion.</p><ol><li>Make sure you have good test coverage (Our current project uses pytest testing framework for this. <a href="https://docs.pytest.org/en/latest/">Reference</a>)</li><li>Learn the differences between Python 2 &amp; 3 (<a href="https://docs.python.org/3.0/whatsnew/3.0.html">Reference</a>)</li><li>Use <a href="https://pypi.org/project/pylint">Pylint</a> to help make sure you don’t introduce linting mistakes</li><li>Make sure any python library used is compatible with Python 3 as well</li><li>Finally, run the <a href="https://docs.python.org/2/library/2to3.html">2to3</a> Python auto-translation tool on the codebase</li></ol><h3>1. Make sure unit tests are written (Pytest)</h3><p>First, <strong>make sure the project has unit tests written at least for main core components. If not start writing unit tests</strong>, otherwise there’s no way of verifying all the components and functions are working as intended after the Python 3 migration. <strong>You may think it as a burden but trust me this will definitely help you, writing unit tests is fun and one of the most important qualities that all software engineers should adapt to their work life.</strong> Since this is a crucial Python component that runs in production and any anomalies or bugs should be introduced with the migration this initial step is highly needed.</p><h3>2. First, learn the differences in Python 3.</h3><p>Without blindly using tools for conversion always try to get the knowledge and pass that knowledge to other developers as well. You can refer to so many online materials on this. I recommend <a href="https://docs.python.org/3.0/whatsnew/3.0.html">this</a>. With my experience in Python 3 migration, I faced a lot of issues regarding<em> Python 3.0 using the concepts of text and (binary) data instead of Unicode strings and 8-bit strings</em>. And also some module names were changed and I had to change them. For example, see the following table. Don’t worry you don’t need to go through all the code base module imports, we can get the help of Python 3 <em>pylint</em> and <em>2to3 </em>tools. They will notify you about those changes automatically. I’ll later explain bit more.</p><pre>┌────────────────────┬──────────────┐<br>│      Old Name      │   New Name   │<br>├────────────────────┼──────────────┤<br>│ _winreg            │ winreg       │<br>│ ConfigParser       │ configparser │<br>│ copy_reg           │ copyreg      │<br>│ Queue              │ queue        │<br>│ SocketServer       │ socketserver │<br>│ markupbase         │ _markupbase  │<br>│ repr               │ reprlib      │<br>│ test.test_support  │ test.support │<br>└────────────────────┴──────────────┘</pre><h3>3. Setup pylint for Python 3 and set up the local dev environment</h3><p>Before starting any conversion you need to set up your local environment to suit Python 3. I use Ubuntu 18.04 OS and VS code as the IDE for my developments. In Ubuntu 18.04 is Python 3 already there. But if you use Windows or any other OS first install Python 3 interpreter first. But pip3 is not available out of the box. So we need to install it. Pip3 is the package management system for Python3 artifacts.</p><h4>Installing pip3 (globally in your OS)</h4><p>Downloading get-pip.py file for pip installation</p><pre>curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py</pre><p>To install pip3 run the downloaded get-pip.py file using Python 3 interpreter.</p><pre>python3 get-pip.py</pre><p>Now that you’ve installed pip3 let’s set up virtual environments for the development. It’s always good to create and work on Python virtual environments without spoiling the OS.</p><p>Create a virtual environment for development.</p><pre>pip3 install virtualenv</pre><pre>python3 virtualenv python3-venv</pre><p>The name of the virtual environment that I gave was python3-venv.</p><p>Now let’s activate the virtual environment.</p><pre>. python3-venv/bin/activate</pre><p>Note → Yes there’s a dot in the above command.</p><p>Now since you have activated the virtual environment your default Python interpreted and pip is set for Python 3. To check it just type python -V, and pip -V.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESik-XdwN2rb5DsHzcn_qw.png" /></figure><p>Now you can install <a href="https://pypi.org/project/pylint/">pylint</a> in the virtual environment using pip.</p><pre>pip install pylint</pre><p>Running pylint on the entire code base. Created a simple bash script called pyilnt.sh</p><pre>#!/usr/bin/env bash</pre><pre>find [enter_root_module]/ -iname &quot;*.py&quot; | xargs pylint $1 $2 $3</pre><p>You can use your root level directory name in the script and it will recursively find all the .py files in the entire project.</p><h4>Running pylint command</h4><pre>./pylint.sh --disable=R,C,W</pre><p>to disable all the <em>Warning</em>, <em>Convention</em>, and <em>Refactoring</em> messages. I right now consider only <em>Errors. </em>This will output the results as below. (I only include sample outputs to give you an idea)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*Y3oDXZzdbzrg56JN2vS3cQ.png" /></figure><p>Now that we have an idea where our code breaks in Python 3. We’ll next run 2to3 tool to see the output.</p><h4>Installing the 2to3 tool and running 2to3</h4><pre>sudo apt-get install -y 2to3</pre><p>Now we’ll create a script to run 2to3 inspection for the whole codebase. Create a file named 2to3_convertor.sh</p><pre>#!/usr/bin/env bash</pre><pre>find [enter_root_module]/ -iname &quot;*.py&quot; | xargs 2to3</pre><h4>Run 2to3</h4><pre>./2to3_convertor.sh</pre><p>Now let’s see the output. I’m not going to share all the details here. But get an idea about the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*HkXEi2_iwNgo5SXRwnyuIw.png" /></figure><p>Note → here I’m not auto fixing the errors. It’s better for the developer to manually go through all the errors and manually fix the code. If you want to auto fix the code you can pass -w flag to 2to3 tool and allow the tool to fix the code. Refer 2to3 man page for more info.</p><p>After fixing all the code now it’s the time to test everything work as expected.</p><p><strong>Now comes the importance of unit tests. If you run units tests again it should not fail.</strong></p><p>In the next article, I’ll share how I test the agent in the Ubuntu OS <em>not locally we cannot test it in local computers</em>. The agent works only on the remote devices which run on Ubuntu 14,04 and 18.04</p><p>Next article →<a href="https://medium.com/@chamaral/how-the-python-3-upgrade-happened-remotely-to-all-those-ubuntu-devices-ab160809046b"> https://medium.com/@chamaral/how-the-python-3-upgrade-happened-remotely-to-all-those-ubuntu-devices-ab160809046b</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6119cbafba26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/converting-process-of-python-2-project-to-python-3-6119cbafba26">Converting process of Python 2 project to Python 3</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How the Python 3 upgrade happened remotely to all those Ubuntu devices]]></title>
            <link>https://medium.com/@chamaral/how-the-python-3-upgrade-happened-remotely-to-all-those-ubuntu-devices-ab160809046b?source=rss-7b87a501d85b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab160809046b</guid>
            <category><![CDATA[upgrade]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[debian]]></category>
            <dc:creator><![CDATA[Chamara Madhushan Liyanage]]></dc:creator>
            <pubDate>Sun, 22 Mar 2020 09:10:38 GMT</pubDate>
            <atom:updated>2020-03-22T09:10:38.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*mDkmV8ZMMXoO2I4Vuo_pjQ.png" /></figure><p>Please read these articles before starting Article 1, Article 2</p><p>As I mentioned earlier this Python agent needs its own environment to run and there’s no way of running the agent software in local development environments or in servers.</p><p>In making the Python 3 agent ready for deployment few decisions had to be made.</p><ol><li>Creating a virtual environment for the agent and isolate it from the global environment</li><li>Remote upgrading mechanisms for all the 10,000+ devices.</li></ol><h4>Creating a virtual environment for the agent</h4><p>The agent is running in heterogeneous environments (Ubuntu 14.04 and Ubuntu 18.04). The main challenge was that in Ubuntu 14.04 the default Python 3 version is Python 3.4 again which was deprecated. (This is another issue faced during the migration project and I’m not going to explain how I tackled the problem in this article since it over-complicate the flow). Let’s only focus on how the virtual environments were created in Ubuntu 18.04 remote devices.</p><p>The previous agent which ran on Python 2 used the global scope of the OS and we decided not to spoil the global OS environment with Python 3 migration. So we planned to install this agent in the virtual environment and utilize this isolated environment for its purposes.</p><p>These devices which I’m not going to share many details about are going to get upgrades using a similar mechanism like Debian OS upgrade that is using a Debian file. Creating a Debian file is out of scope in this article I’ll create a separate article on this.</p><p>Think a Debian file as some executable file like (.exe file in Windows, you can install things using that file in your OS). There were 2 Debian files created for this migration. I’ll name these files as Debian 1 and Debian 2 for simplicity.</p><h4>Debian 1 — It’s basically to install all the pre-requisites needed by Python 3 agents.</h4><p>It does the following tasks during the installation.</p><ul><li>Installing pip3 (since Ubuntu does not ship with pip3 by default)</li><li>Creating a virtual environment for the new agent software</li><li>Installing dependencies needed by the agent. (There are about 10+ python libraries needed by this agent and those are installed using pip3 in the virtual environment)</li></ul><blockquote>Note → During this Debian 1 installation the current Python 2 agent is not hindered in production and it runs in the background.</blockquote><h4>Debian 2 — It’s the new Python 3 agent software.</h4><p>This Debian does the following tasks upon its installation.</p><ul><li>First, it stops the current Python 2 agent (not the production Device just the service of the agent)</li><li>Change some configuration files ( like upstart/systemd service files)</li><li>Uninstalls the old deprecated Python 2 agent</li><li>Installs the new Python 3 agent which is packed in the Debian 2 in the new virtual environment created during the Debian 1 installation.</li><li>Starts the new Python 3 agent software.</li></ul><blockquote>Note → This whole process takes less than 5 seconds and downtime is minimal. (One of the reasons to send 2 Debians in 2 OS upgrades make this minimal downtime achievable)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab160809046b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are styled components]]></title>
            <link>https://medium.com/@chamaral/what-are-styled-components-10914a80594a?source=rss-7b87a501d85b------2</link>
            <guid isPermaLink="false">https://medium.com/p/10914a80594a</guid>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Chamara Madhushan Liyanage]]></dc:creator>
            <pubDate>Tue, 18 Sep 2018 12:11:29 GMT</pubDate>
            <atom:updated>2018-09-18T12:12:45.513Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/318/0*hZVviBH2tjLtiAat.png" /></figure><p>Styled components are React components which are already styled. For styling we use CSS and styled-component library allows us to write a component in react which can be styled with CSS. In other words CSS written in JavaScript file. This is awesome and has lot of advantages when creating React applications. Let’s see how awesome this is.</p><p>First create a sample react app using create-react-app. I use yarn so,</p><pre>yarn create react-app my-app</pre><p><a href="https://github.com/facebook/create-react-app">GitHub - facebook/create-react-app: Set up a modern web app by running one command.</a></p><p>After installing let’s install styled-components using npm. In your project root run</p><pre>npm install --save styled-components</pre><p>Then go to the src/App.js . Let’s edit this file and learn styled components for simplicity.</p><p>Let’s understand the concept of styled-component using a Button example.</p><p>import styled-component in App.js file.</p><pre><em>import</em> styled<em> from</em> &#39;styled-components&#39;;</pre><p>Then create a button using styled-components like this.</p><pre>const Button = styled.button``</pre><p>You can use styled.xxx xxx can be any html element. If you want img then styled.img and so on. Here after styled.button we use backticks. Backtick syntax is a new JavaScript feature called a tagged template literal. Now we have created a Button component using styled-component and it’s so simple.</p><p>The whole App.js file will look like this. I’ve removed unncessary code in App.js file so it’s clear.</p><pre>import React, { Component } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import styled from &#39;styled-components&#39;;</pre><pre>const Button = styled.button``</pre><pre>class App extends Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>       <br>        &lt;Button&gt;Normal Button&lt;/Button&gt;</pre><pre>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default App;</pre><p>To see the output yarn start and go to localhost:3000 and then you will see an output like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Jrp8Qk5kpM8Z1sNPgkn1kQ.png" /><figcaption>figure-1</figcaption></figure><p>Yahh this is the button we created. Lets style the button a bit. What we have to do is style the component call Button in our code.</p><pre>const Button = styled.button`<br>  border-radius: 3px;<br>  padding: 0.25em 1em;<br>  margin: 2em 1em;<br>  background: red;<br>`</pre><p>Now we have added some CSS to button inside those backticks. Now lets see how the output looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*zDAhwA7psoL0aRfDnxinUg.png" /><figcaption>figure-2</figcaption></figure><p>You can write any CSS like this in your styled-component . Let’s now see how to change the properties of &lt;Button&gt; component using props logic in React.</p><p>What I want is to make buttons look different based on the props that I pass.</p><pre>&lt;Button primary&gt;Red Button&lt;/Button&gt;<br>&lt;Button&gt;Other Button&lt;/Button&gt;</pre><p>I use the same &lt;Button&gt; but one is given the property primary . I can give whatever name I want to the prop. Let’s say I want primary button to look in red color and other normal buttons to look green then lets add some logic to out Button component based on the prop value that we pass.</p><pre>const Button = styled.button`<br>  border-radius: 3px;<br>  padding: 0.25em 1em;<br>  margin: 2em 1em;<br>  background: ${ props =&gt; (props.primary ? &quot;red&quot; : &quot;green&quot;)};<br>`</pre><p>Here we can use as props.primary to check if there’s a prop passed with the name primary . Based on that we change the color of the button to red or green.</p><p>The whole code look like this now.</p><pre>import React, { Component } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import styled from &#39;styled-components&#39;;</pre><pre>const Button = styled.button`<br>  border-radius: 3px;<br>  padding: 0.25em 1em;<br>  margin: 2em 1em;<br>  background: ${ props =&gt; (props.primary ? &quot;red&quot; : &quot;green&quot;)};<br>`</pre><pre>class App extends Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;  <br>        &lt;Button primary&gt;Red Button&lt;/Button&gt;<br>        &lt;Button&gt;Other Button&lt;/Button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default App;</pre><p>The output is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*L8BpykwqBj6gR3927cn2jw.png" /><figcaption>figure-3</figcaption></figure><p>So this is the very basic of what styled-components can do and there are hell lot of other useful and use cases out there.</p><p><a href="https://www.styled-components.com/">https://www.styled-components.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10914a80594a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Too many terminal windows and can’t find what’s what, well use TERMINATOR]]></title>
            <link>https://medium.com/hackernoon/too-many-terminal-windows-and-cant-find-what-s-what-aea26363c0ef?source=rss-7b87a501d85b------2</link>
            <guid isPermaLink="false">https://medium.com/p/aea26363c0ef</guid>
            <category><![CDATA[terminal-windows]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[terminator]]></category>
            <category><![CDATA[use-terminator]]></category>
            <dc:creator><![CDATA[Chamara Madhushan Liyanage]]></dc:creator>
            <pubDate>Sat, 16 Jun 2018 13:27:17 GMT</pubDate>
            <atom:updated>2018-06-16T20:13:52.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuSxnLMVuV7pP-wCUPZ9XA.png" /></figure><p>If you are working in a Linux distribution or a mac you probably have run into the problem where you have opened too many terminals and can’t figure out what was doing what. That’s because you cant nicely split terminals as you want and you can’t name your terminal. I faced this problem when I had to work with several servers. I had to open more than 4 terminal windows to connect to different server instances and found out very difficult when switching among them. Also I had no way to rename my terminal windows to identify them.</p><p>Then I found out this solution and it’s really awesome and I want share it with you guys and I know it’ll be definite help for you as well.</p><h3>It’s the TERMINATOR.</h3><p>Yesss, the application name is terminator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*reKBGAYBalDYqkWu.jpg" /></figure><p>Ubuntu installation</p><pre>sudo add-apt-repository ppa:gnome-terminator<br>sudo apt-get update<br>sudo apt-get install terminator</pre><p>Then search for Terminator app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pISN_5lC0mAbJQV01NgRQ.png" /></figure><p>Here is it’s magic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gV2MWNoZqt_BQI7VmMdyzw.png" /></figure><p>You can right click on terminator terminal and choose the option to split horizontally or vertically. Also you can double click on any terminal title bar and rename as you wish.</p><p>Hope this tiny information helps you guys in managing you terminals.</p><p>Cheers !!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aea26363c0ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/too-many-terminal-windows-and-cant-find-what-s-what-aea26363c0ef">Too many terminal windows and can’t find what’s what, well use TERMINATOR</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Redis with Node JS]]></title>
            <link>https://medium.com/hackernoon/using-redis-with-node-js-8d87a48c5dd7?source=rss-7b87a501d85b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d87a48c5dd7</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[redis-with-node-js]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Chamara Madhushan Liyanage]]></dc:creator>
            <pubDate>Sun, 08 Apr 2018 04:23:55 GMT</pubDate>
            <atom:updated>2019-04-08T16:10:12.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/604/0*ia_gKRqbfM5xyYDJ.jpg" /></figure><h4>What is Redis</h4><p><a href="https://redis.io/">Redis</a> is an in-memory data structure store which can be used as a database, a cache and a message broker. Redis supports different data structures such as strings, lists, sets, hashes, bitmaps and etc. . Simply Redis uses you RAM to store data which is very fast, however if you reboot your server the values are gone, unless you enable R<a href="https://redis.io/topics/persistence">edis persistence</a>. Good news by default Redis enables persistence mechanism for you (you can disable or configure persistence according to your needs.)</p><h4>Install Redis (Linux)</h4><p>Refer: <a href="https://redis.io/download">https://redis.io/download</a></p><p><em>Download, extract and compile Redis with:</em></p><pre>$ wget http://download.redis.io/releases/redis-4.0.9.tar.gz<br>$ tar xzf redis-4.0.9.tar.gz<br>$ cd redis-4.0.9<br>$ make</pre><p><em>The binaries that are now compiled are available in the </em><em>src directory. Run Redis with:</em></p><pre>$ src/redis-server</pre><p>You can interact with Redis using the built-in client:</p><pre>$ src/redis-cli<br>redis&gt; set foo bar<br>OK<br>redis&gt; get foo<br>&quot;bar&quot;</pre><p>OK, now we have successfully installed Redis on the local machine. <a href="https://redis.io/commands">Here</a> you can see useful <a href="https://redis.io/commands">commands</a> that we can use with Redis. They are super simple and helpful. Spend some time with those commands.</p><h4>Using Redis in your NodeJS application</h4><p>First you need to install the Redis client for NodeJS via <a href="https://www.npmjs.com/package/redis">npm</a>.</p><pre>npm install redis</pre><p>Now create a file called redisDemo.js in your NodeJS project.</p><pre>// redisDemo.js<br>var redis = require(&#39;redis&#39;);<br>var client = redis.createClient(); // this creates a new client</pre><p>By default redis.createClient() will use 127.0.0.1 and port 6379. If you have a customized ip and and a port use</p><pre>var client = redis.createClient(port, host);</pre><p>Now, we want to listen for the <em>connect</em> event to see whether we successfully connected to the redis-server. We can check for a successful connection like this.</p><pre>client.on(&#39;connect&#39;, <strong>function</strong>() {<br>    console.log(&#39;Redis client connected&#39;);<br>});</pre><p>Likewise, we want to check if we failed to connect to the redis-server. Well we can listen for the <em>error</em> event for that.</p><pre>client.on(&#39;error&#39;, <strong>function </strong>(err) {<br>    console.log(&#39;Something went wrong &#39; + err);<br>});</pre><p>This might trigger when you forget to start the <em>redis-server</em> before application is run.<em> </em>So make sure to run the redis server before testing this code.</p><p>Note: you can start, stop the redis server using following commands.</p><pre>/etc/init.d/redis-server stop<br>/etc/init.d/redis-server start</pre><p>Let’s see how our code looks like now.</p><pre><strong>var </strong>redis = require(&#39;redis&#39;);<br><strong>var </strong>client = redis.createClient();<br><br>client.on(&#39;connect&#39;, <strong>function</strong>() {<br>    console.log(&#39;Redis client connected&#39;);<br>});<br><br>client.on(&#39;error&#39;, <strong>function </strong>(err) {<br>    console.log(&#39;Something went wrong &#39; + err);<br>});</pre><p>Now, Let’s see how to set some simple value under a key in redis. You can use set() and get() methods for that.</p><pre>client.set(&#39;my test key&#39;, &#39;my test value&#39;, redis.print);<br>client.get(&#39;my test key&#39;, <strong>function </strong>(error, result) {<br>    <strong>if </strong>(error) {<br>        console.log(error);<br>        <strong>throw </strong>error;<br>    }<br>    console.log(&#39;GET result -&gt;&#39; + result);<br>});</pre><p>in client.set() we first give the key and then the value. Remember Redis is a key-value store. Redis will create a key named <em>‘my test key’ </em>and assign the value <em>‘my test value’</em> for that key.</p><p>You see that I’ve used that <em>redis.print </em>on set() method. well it prints “Reply: OK” to the console saying that redis saved the value. you can omit that argument if you want.</p><p>Now in get() method we simply retrieve the value we just saved by specifying the exact key name. Then it will print the saved valued in the console.</p><p>Let’s see the complete code now.</p><pre><strong>var </strong>redis = require(&#39;redis&#39;);<br><strong>var </strong>client = redis.createClient();<br><br>client.on(&#39;connect&#39;, <strong>function</strong>() {<br>    console.log(&#39;Redis client connected&#39;);<br>});<br><br>client.on(&#39;error&#39;, <strong>function </strong>(err) {<br>    console.log(&#39;Something went wrong &#39; + err);<br>});<br><br>client.set(&#39;my test key&#39;, &#39;my test value&#39;, redis.print);<br>client.get(&#39;my test key&#39;, <strong>function </strong>(error, result) {<br>    <strong>if </strong>(error) {<br>        console.log(error);<br>        <strong>throw </strong>error;<br>    }<br>    console.log(&#39;GET result -&gt;&#39; + result);<br>});</pre><p>The output will look like this</p><pre>Redis client connected<br>Reply: OK<br>GET result -&gt;my test value</pre><h4>Conclusion</h4><p>Redis is very powerful in-memory data-store that we can use in our applications. It’s very simple to save and get data without much overhead. refer <a href="https://www.npmjs.com/package/redis">https://www.npmjs.com/package/redis</a> for more use cases and refer <a href="https://redis.io/commands">https://redis.io/commands</a> for more redis commands.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fdde502%2F&amp;image=https%3A%2F%2Fucarecdn.com%2F57662ddc-da7c-407b-afcb-cb45184b2705%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d25dd15e8727342107fbe0b6d67b030e/href">https://medium.com/media/d25dd15e8727342107fbe0b6d67b030e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d87a48c5dd7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/using-redis-with-node-js-8d87a48c5dd7">Using Redis with Node JS</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API testing using SuperTest]]></title>
            <link>https://medium.com/hackernoon/api-testing-using-supertest-1f830ce838f1?source=rss-7b87a501d85b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f830ce838f1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rest-api-testing]]></category>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[supertest]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Chamara Madhushan Liyanage]]></dc:creator>
            <pubDate>Sat, 31 Mar 2018 13:54:39 GMT</pubDate>
            <atom:updated>2018-04-09T16:50:17.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xMaFF2hSXpf_kIfG.jpg" /></figure><p>Wonder how to write tests for you API. Well you can use <a href="https://www.npmjs.com/package/supertest">SuperTest</a> which is can be used to test HTTP endpoints.</p><p>Before starting <strong>SuperTest</strong> let’s create a simple API using node + express. In express let’s use the the route given to us by them in order to learn <strong>SuperTest</strong> library. This article is not focusing on crating a rest API using express framework.</p><p>Let’s go to the /routes/users.js file and create some endpoints.</p><pre><strong>var </strong>express = require(&#39;express&#39;);<br><strong>var </strong>router = express.Router();<br><br><em>/**<br> * get all users<br> */<br></em>router.get(&#39;/&#39;, <strong>function </strong>(req, res, next) {<br>    <strong>return </strong>res.json(&#39;all users sent&#39;);<br>});<br><br><em>/**<br> * Get a specific user<br> */<br></em>router.get(&#39;/:id&#39;, <strong>function </strong>(req, res, next) {<br>    <strong>if </strong>(req.params.id === &#39;U001&#39;) { // just to demo<br>        <strong>return </strong>res.json(&quot;user U001 found&quot;);<br>    }<br>    <strong>return </strong>res.status(404).json(&#39;user not found&#39;);<br>});<br><br><em>/**<br> * Add a user<br> */<br></em>router.post(&#39;/&#39;, <strong>function </strong>(req, res, next) {<br>    <strong>let </strong>content = req.body;<br>    <strong>if </strong>(content.id) { //just to demo<br>        <strong>return </strong>res.status(201).json(&quot;user created&quot;);<br>    }<br>    <strong>return </strong>res.status(400).json(&#39;user not created&#39;);<br>});<br><br>module.exports = router;</pre><p>I’ve crated two simple get methods to fetch user data and a post method to save a user. LOL, I was kidding there’s no actual database integration or save functionality just sending some JSON outputs based on some dummy logic 😹 and status codes to test our API. You can create a real working API. But remember to send relevant <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP status codes</a> so it’s easy when writing unit tests later.</p><p>Now let’s focus on writing API tests using <strong>SuperTest</strong>. First you need to install the dependency as a devDependancy.</p><pre>npm install supertest --save-dev</pre><p>This will include mocha as well because super test use mocha test framework. But you don’t need to install it it comes with <strong>supertest</strong>.</p><p>Then lets create a directory called <em>test </em>in the root level of the project and create a file called <em>apiTest.js. </em>This file is the file where we write the API tests.</p><p>First thing we need is the supertest module.</p><pre>//apiTest.js<br>const request = require(&#39;supertest&#39;);</pre><p>Then we need to pass the http.Server to the request() method of supertest. To do that let’s include our express app as follows.</p><pre>//apiTest.js<br>const request = require(&#39;supertest&#39;);<br>const<strong> </strong>app = require(&#39;../app&#39;); //reference to you app.js file</pre><p>The let’s write the first API test to test the <a href="http://localhost:3000/users">http://localhost:3000/users</a> endpoint . If this endpoint works correctly it should return status code 200. That’s how the user route file is implemented . See the following code res.json() will automatically set the status code 200. So no worries.</p><pre><em>//from users.js route file<br>/**<br> * get all users<br> */<br></em>router.get(&#39;/&#39;, <strong>function </strong>(req, res, next) {<br>    <strong>return </strong>res.json(&#39;all users sent&#39;);<br>});</pre><p>Ok, how we write the test for this route in out apiTest.js using supertest.</p><pre>//apiTest.js<strong><br>const </strong>request = require(&#39;supertest&#39;);<br><strong>const </strong>app = require(&#39;../app&#39;);<br><br>//==================== user API test ====================<br><br><em>/**<br> * Testing get all user endpoint<br> */<br></em>describe(&#39;GET /users&#39;, <strong>function </strong>() {<br>    it(&#39;respond with json containing a list of all users&#39;, <strong>function </strong>(done) {<br>        request(app)<br>            .get(&#39;/users&#39;)<br>            .set(&#39;Accept&#39;, &#39;application/json&#39;)<br>            .expect(&#39;Content-Type&#39;, /json/)<br>            .expect(200, done);<br>    });<br>});</pre><p>Here <strong>describe</strong> method is coming from mocha test framework. We simply specify the endpoint name as the first argument and then the function to write the test case. Here Mocha <strong>describe</strong>() is for grouping the test cases while <strong>it</strong>() is used to write the real test cases. We give a simple description of what we are going to test as the first argument in it() function. Then the callback function to be called.</p><p><strong>request</strong>() needs the HTTP.server so we pass our express app reference. Then in <strong>get</strong>() we specify the route endpoint. Here we are in the app so can omit <a href="http://localhost:3000/">http://localhost:3000/</a> part. Just give the route endpoint.</p><p>in <strong>set</strong>() we set the HTTP header attributes. Then in <strong>expect</strong>() we check for the return values including Header values and body values.</p><p>In this example we check whether the returned content type is JSON. Because we send the response as JSON using res.json() method. Then expect(200) is to check the returned status code is equal to 200. Then we end the test by calling <em>done </em>our callback function.</p><p>Right so far so good. But how can we run this tests. Well you have to use make this change in your <em>package.json</em> file.</p><pre>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;node ./bin/www&quot;,<br>  &quot;test&quot;: &quot;mocha &#39;test/apiTest.js&#39;&quot; //path to your test file<br>}</pre><p>Now you can run the test cases by simply using</p><pre>&gt; npm test</pre><p>After running the test file you’ll see this output.</p><pre>&gt; mocha &#39;test/apiTest.js&#39;</pre><pre>GET /users<br>GET /users 200 5.289 ms - 16<br>    ✓ respond with json containing a list of all users</pre><pre>1 passing (38ms)</pre><p>Let’s continue writing more test cases of all the endpoints in the users.js file.</p><pre><strong>const </strong>request = require(&#39;supertest&#39;);<br><strong>const </strong>app = require(&#39;../app&#39;);<br><br>//==================== user API test ====================<br><br><em>/**<br> * Testing get all user endpoint<br> */<br></em>describe(&#39;GET /users&#39;, <strong>function </strong>() {<br>    it(&#39;respond with json containing a list of all users&#39;, <strong>function </strong>(done) {<br>        request(app)<br>            .get(&#39;/users&#39;)<br>            .set(&#39;Accept&#39;, &#39;application/json&#39;)<br>            .expect(&#39;Content-Type&#39;, /json/)<br>            .expect(200, done);<br>    });<br>});<br><br><em>/**<br> * Testing get a user endpoint by giving an existing user<br> */<br></em>describe(&#39;GET /user/:id&#39;, <strong>function </strong>() {<br>    it(&#39;respond with json containing a single user&#39;, <strong>function </strong>(done) {<br>        request(app)<br>            .get(&#39;/users/U001&#39;)<br>            .set(&#39;Accept&#39;, &#39;application/json&#39;)<br>            .expect(&#39;Content-Type&#39;, /json/)<br>            .expect(200, done);<br>    });<br>});<br><br><em>/**<br> * Testing get a user endpoint by giving a non-existing user<br> */<br></em>describe(&#39;GET /user/:id&#39;, <strong>function </strong>() {<br>    it(&#39;respond with json user not found&#39;, <strong>function </strong>(done) {<br>        request(app)<br>            .get(&#39;/users/idisnonexisting&#39;)<br>            .set(&#39;Accept&#39;, &#39;application/json&#39;)<br>            .expect(&#39;Content-Type&#39;, /json/)<br>            .expect(404) //expecting HTTP status code<br>            .expect(&#39;&quot;user not found&quot;&#39;) // expecting content value<br>            .end((err) =&gt; {<br>                <strong>if </strong>(err) <strong>return </strong>done(err);<br>                done();<br>            });<br>    });<br>});<br><br><em>/**<br> * Testing post user endpoint<br> */<br></em>describe(&#39;POST /users&#39;, <strong>function </strong>() {<br>    <strong>let </strong>data = {<br>        &quot;id&quot;: &quot;1&quot;,<br>        &quot;name&quot;: &quot;dummy&quot;,<br>        &quot;contact&quot;: &quot;dummy&quot;,<br>        &quot;address&quot;: &quot;dummy&quot;<br>    }<br>    it(&#39;respond with 201 created&#39;, <strong>function </strong>(done) {<br>        request(app)<br>            .post(&#39;/users&#39;)<br>            .send(data)<br>            .set(&#39;Accept&#39;, &#39;application/json&#39;)<br>            .expect(&#39;Content-Type&#39;, /json/)<br>            .expect(201)<br>            .end((err) =&gt; {<br>                <strong>if </strong>(err) <strong>return </strong>done(err);<br>                done();<br>            });<br>    });<br>});<br><br><em>/**<br> * Testing post user endpoint<br> */<br></em>describe(&#39;POST /users&#39;, <strong>function </strong>() {<br>    <strong>let </strong>data = {<br>        //no id<br>        &quot;name&quot;: &quot;dummy&quot;,<br>        &quot;contact&quot;: &quot;dummy&quot;,<br>        &quot;address&quot;: &quot;dummy&quot;<br>    }<br>    it(&#39;respond with 400 not created&#39;, <strong>function </strong>(done) {<br>        request(app)<br>            .post(&#39;/users&#39;)<br>            .send(data)<br>            .set(&#39;Accept&#39;, &#39;application/json&#39;)<br>            .expect(&#39;Content-Type&#39;, /json/)<br>            .expect(400)<br>            .expect(&#39;&quot;user not created&quot;&#39;)<br>            .end((err) =&gt; {<br>                <strong>if </strong>(err) <strong>return </strong>done(err);<br>                done();<br>            });<br>    });<br>});</pre><p>If you look closely at the code in <em>apiTest.js</em> file you’ll get the rhythm. I’ve only showed GET and POST methods but you can try PUT and DELETE methods with real working API.</p><p>If you run this test file using <em>npm test </em>command finally you’ll see an output like this.</p><pre>&gt; mocha &#39;test/apiTest.js&#39;<br>GET /users<br>GET /users 200 5.610 ms - 16<br>    ✓ respond with json containing a list of all users</pre><pre>GET /user/:id<br>GET /users/U001 200 0.870 ms - 17<br>    ✓ respond with json containing a single user</pre><pre>GET /user/:id<br>GET /users/idisnonexisting 404 0.458 ms - 16<br>    ✓ respond with json user not found</pre><pre>POST /users<br>POST /users 201 10.196 ms - 14<br>    ✓ respond with 201 created</pre><pre>POST /users<br>POST /users 400 0.607 ms - 18<br>    ✓ respond with 400 not created</pre><pre>5 passing (62ms)</pre><p>Better to refer <a href="https://github.com/visionmedia/supertest">https://github.com/visionmedia/supertest</a> for more knowledge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f830ce838f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/api-testing-using-supertest-1f830ce838f1">API testing using SuperTest</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>