<?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[ramosly | blog - Medium]]></title>
        <description><![CDATA[Adventures in Code :) - Medium]]></description>
        <link>https://medium.com/ramojol?source=rss----d27fe4c47e7c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>ramosly | blog - Medium</title>
            <link>https://medium.com/ramojol?source=rss----d27fe4c47e7c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:23:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/ramojol" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Fix “session deleted because of page crash” when using Selenium Grid and Docker]]></title>
            <link>https://medium.com/ramojol/fix-session-deleted-because-of-page-crash-when-using-selenium-grid-and-docker-61ab1749ab8d?source=rss----d27fe4c47e7c---4</link>
            <guid isPermaLink="false">https://medium.com/p/61ab1749ab8d</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[selenium-grid]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[webdriverio]]></category>
            <dc:creator><![CDATA[Joel Ramos]]></dc:creator>
            <pubDate>Fri, 19 Mar 2021 14:01:35 GMT</pubDate>
            <atom:updated>2021-03-19T14:01:32.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ufMA_q8vJBtQu9dM.png" /></figure><p>Recently I created a CI pipeline that stands up a local selenium grid and then pipeline jobs run WebdriverIO tests against that selenium grid.</p><p>I noticed that when I ran more than a single feature file in parallel, that the first process for the first feature file would succeed, but all others would fail with the following error saying something about the page crashing:</p><pre><br>[0-5] 2021-03-16T18:49:58.094Z WARN webdriver: Request failed with status 500 due to unknown error: session deleted because of page crash                                     <br>from unknown error: cannot determine loading status                                                                                                                           <br>from tab crashed                                                                                                                                                              <br>  (Session info: chrome=89.0.4389.82)                                                                                                                                         <br>[0-5] 2021-03-16T18:49:58.103Z ERROR webdriver: Request failed with status 404 due to invalid session id: invalid session id</pre><p>From then on, WebDriver would log that it was trying to connect to the session but not finding the session id and timing out.</p><pre>[0-5] 2021-03-16T18:49:58.118Z WARN webdriver: Request failed with status 500 due to Session [cdc0c2a1ee9d791bd13827a53754de91] was terminated due to BROWSER_TIMEOUT         <br>[0-5] 2021-03-16T18:49:58.124Z WARN webdriver: Request failed with status 500 due to Session [cdc0c2a1ee9d791bd13827a53754de91] was terminated due to BROWSER_TIMEOUT         <br>[0-5] 2021-03-16T18:49:58.129Z ERROR webdriver: Request failed with status 500 due to unknown error: Session [cdc0c2a1ee9d791bd13827a53754de91] was terminated due to BROWSER_<br>TIMEOUT</pre><p>The selenium grid was configured to allow 20 concurrent sessions, as was the single Chrome node, so I was perplexed!</p><pre>selenium_hub:<br>  image: selenium/hub<br>  ports:<br>    - 4444<br>  environment:<br>    - SE_OPTS=-debug<br>    - GRID_MAX_SESSION=20<br>    - GRID_BROWSER_TIMEOUT=10000<br>    - GRID_TIMEOUT=10000<br>chrome:<br>  image: selenium/node-chrome<br>  depends_on:<br>    - selenium_hub<br>  environment: <br>    - NODE_MAX_SESSION=20<br>    - NODE_MAX_INSTANCES=20<br>    - HUB_HOST=selenium_hub<br>    - HUB_PORT=4444</pre><p>I was looking into this with a coworker when I googled the error message and came across this <a href="https://stackoverflow.com/a/53970825">StackOverflow answer</a>, which pointed me to this <a href="https://github.com/elgalu/docker-selenium/issues/20">github issue</a> which tipped me off that, “… recent version(s) of <em>Chrome seem to crash in Docker containers, on certain pages, due to too small /dev/shm.</em>”</p><p>Given this limitation, there were a few ways to handle this</p><ul><li>Increase the size of /dev/shm with the --shm-size option (I believe shm stands for <a href="https://www.cyberciti.biz/tips/what-is-devshm-and-its-practical-usage.html">shared memory</a>)</li><li>Mount /dev/shm:/dev/shm from the host to the container</li><li>Disable /dev/shm via the --disable-dev-shm-usage option so that the disk is used instead of memory, which can make things slower.</li></ul><p>I decided to go with the 3rd option since memory is also limited in the CI context. I might change it in the future, but for now it works.</p><p>The StackOverflow answer also suggests adding the --no-sandbox option, which should be fine as long as you trust the websites your browser will be visiting.</p><p>In the context of WebdriverIO, I added these in the capabilities for Chrome:</p><pre>capabilities: [<br>  {<br>    browserName: &#39;chrome&#39;,<br>    &#39;goog:chromeOptions&#39;: {<br>      args: [<br>        &#39;--no-sandbox&#39;,<br>        &#39;--disable-dev-shm-usage&#39;,<br>        &#39;--disable-gpu&#39;,<br>        &#39;--window-size=1920,1080&#39;,<br>      ],<br>    },<br>  }<br>...<br>]</pre><p>Once I added these options, it worked! 🎉</p><p>This should also be true if you’re using some other WebDriver-based framework or using another language since this is ultimately related to running the Chrome browser in the context of a Docker container.</p><p>Hopefully this helps someone else out there running into this.</p><h3>Links</h3><ul><li><strong>StackOverflow Question</strong>: <a href="https://stackoverflow.com/questions/53902507/unknown-error-session-deleted-because-of-page-crash-from-unknown-error-cannot">unknown error: session deleted because of page crash from unknown error: cannot determine loading status from tab crashed with ChromeDriver Selenium</a></li><li><strong>Github Issue</strong>: <a href="https://github.com/elgalu/docker-selenium/issues/20">UnknownError: session deleted because of page crash from tab crashed #20</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61ab1749ab8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ramojol/fix-session-deleted-because-of-page-crash-when-using-selenium-grid-and-docker-61ab1749ab8d">Fix “session deleted because of page crash” when using Selenium Grid and Docker</a> was originally published in <a href="https://medium.com/ramojol">ramosly | blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Versioning with semantic-release]]></title>
            <link>https://medium.com/ramojol/versioning-with-semantic-release-d589aba7e628?source=rss----d27fe4c47e7c---4</link>
            <guid isPermaLink="false">https://medium.com/p/d589aba7e628</guid>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[release-management]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[semantic-versioning]]></category>
            <dc:creator><![CDATA[Joel Ramos]]></dc:creator>
            <pubDate>Sat, 14 Nov 2020 18:37:05 GMT</pubDate>
            <atom:updated>2021-03-19T04:39:22.696Z</atom:updated>
            <content:encoded><![CDATA[<h3>Versioning with the Semantic Release GitHub Action</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*tTCFzuu4B0TPWYYusKBmwA.png" /></figure><p>In this post I’ll run through configuring the Semantic Release GitHub Action to automate versioning, create GitHub Releases, and document release notes.</p><p>As I started writing this, it occurred to me that there might be two types of folks reading this.</p><ul><li>One set who just want the answers to the test.</li><li>One that wants to understand what is going on.</li></ul><p>If you’re in the first camp, you can just run through the <strong>TL;DR</strong> section below, and maybe tweak it for your use case if needed, and you should be good to go.</p><h3>TL;DR</h3><h4>Step 1: Configuration</h4><p>Create a .releaserc.json file in the root directory of your repository.</p><p>Then, put this in it:</p><pre>{<br>    &quot;branch&quot;: &quot;master&quot;,<br>    &quot;plugins&quot;: [<br>        [<br>            &quot;@semantic-release/commit-analyzer&quot;,<br>            {<br>                &quot;preset&quot;: &quot;eslint&quot;,<br>                &quot;releaseRules&quot;: [<br>                    { &quot;tag&quot;: &quot;Breaking&quot;, &quot;release&quot;: &quot;major&quot; },<br>                    { &quot;tag&quot;: &quot;Build&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Chore&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Fix&quot;, &quot;release&quot;: &quot;patch&quot; },<br>                    { &quot;tag&quot;: &quot;New&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Update&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Upgrade&quot;, &quot;release&quot;: &quot;minor&quot; }<br>                ]<br>            }<br>        ],<br>        [<br>            &quot;@semantic-release/release-notes-generator&quot;,<br>            {<br>                &quot;preset&quot;: &quot;eslint&quot;,<br>                &quot;releaseRules&quot;: [<br>                    { &quot;tag&quot;: &quot;Breaking&quot;, &quot;release&quot;: &quot;major&quot; },<br>                    { &quot;tag&quot;: &quot;Build&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Chore&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Fix&quot;, &quot;release&quot;: &quot;patch&quot; },<br>                    { &quot;tag&quot;: &quot;New&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Update&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Upgrade&quot;, &quot;release&quot;: &quot;minor&quot; }<br>                ]<br>            }<br>        ],<br>        [<br>            &quot;@semantic-release/changelog&quot;,<br>            {<br>                &quot;changelogFile&quot;: &quot;CHANGELOG.md&quot;<br>            }<br>        ],<br>        &quot;@semantic-release/github&quot;,<br>        [<br>            &quot;@semantic-release/git&quot;, {<br>                &quot;assets&quot;: [&quot;package.json&quot;, &quot;CHANGELOG.md&quot;],<br>                &quot;message&quot;: &quot;chore(release): ${nextRelease.version} [skip ci]\\\\n\\\\n${nextRelease.notes}&quot;<br>            }<br>        ]<br>    ]<br>}</pre><h4>Step 2: GitHub Actions Workflow</h4><p>Create a .github/workflows/release.yml file.</p><p>Then, put this in it:</p><pre>name: Release<br>on:<br>  push:<br>    branches: [ master ]</pre><pre>jobs:<br>  release:<br>    runs-on: ubuntu-latest</pre><pre>    steps:<br>        - name: Checkout<br>          uses: actions/checkout@v2</pre><pre>        - name: Semantic Release<br>          uses: cycjimmy/semantic-release-action@v2<br>          id: semantic<br>          with:<br>            extra_plugins: |<br>              @semantic-release/changelog<br>              @semantic-release/git<br>              conventional-changelog-eslint<br>          env:<br>            GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}</pre><h4>Step 3: Push changes and create a release</h4><p>Now that things are configured, all you need is for your new commits to follow the &quot;releaseRules&quot; that we&#39;ve specified in the .releaserc.json file.</p><p><strong>For example…</strong></p><p>Let’s say we want to commit a new change. Our commit message should follow the format <strong>“New: adds new feature”</strong> where the word <strong>“New”</strong> matches the { &quot;tag&quot;: &quot;New&quot;, &quot;release&quot;: &quot;minor&quot; } release rule.</p><p>When we merge the pull request to the main branch, under our current setup the minor version will be incremented (e.g., from v1.0.0 to v1.1.0)</p><p>Similarly, when we commit a fix with a <strong>“Fix: fix bug 123”</strong> commit message, this will match the { &quot;tag&quot;: &quot;Fix&quot;, &quot;release&quot;: &quot;patch&quot; } release rule and will increment the patch version (e.g., from v1.0.0 to v1.0.1)</p><p>On top of that, a new release and tag will be created, and because we’ve also configured the changelog plugin, the <a href="http://changelog.md/">CHANGELOG.md</a> file will be updated with release notes based on our commit messages.</p><p>And now if we look at the releases in GitHub for the repo, we can see</p><h3>What’s going on here?</h3><p>Let me explain!</p><p>Like most things, if you truly want consistency it’s better to have a machine do it.</p><p>And we could write scripts to get the current version number then bump the version as new changes get merged to the default branch, but honestly who wants to do that?</p><p>Luckily, <a href="https://semantic-release.gitbook.io/semantic-release/">semantic-release</a> and the <a href="https://github.com/marketplace/actions/action-for-semantic-release">Semantic Release Action</a> make it pretty damn easy.</p><h4>☑️ Requirements</h4><p>It was important to know what the desired outcome was. For me, there were three main things to accomplish.</p><ol><li>When changes are merged to the default branch, a new tag should be created with the name being the new version number, along with a GitHub Release.</li><li>Semantic Release should analyze my commits and determine whether to bump the major version, the minor version, or the patch version (i.e., v{major}.{minor}.{patch} → v2.0.1)</li><li>Semantic Release should also update the <a href="http://changelog.md/">CHANGELOG.md</a> file to keep a history of the release notes.</li></ol><h4>🏃 Configuration</h4><p>Next it was time to start doing, so the plan was to start at the local code / configuration, and work my way towards the remote GitHub repository.</p><p>The semantic-release <a href="https://semantic-release.gitbook.io/semantic-release/usage/configuration">configuration</a> can either go in your <em>package.json</em> file, or a separate <em>.releaserc.json</em> file.</p><p>I decided to keep it in its own file. Hopefully this helps people, or future me, find these configurations more easily.</p><p>The .releaserc.json file is where you configure the semantic-release plugins, which by default there are four.</p><ul><li><a href="https://github.com/semantic-release/commit-analyzer">@semantic-release/commit-analyzer</a></li><li><a href="https://github.com/semantic-release/release-notes-generator">@semantic-release/release-notes-generator</a></li><li><a href="https://github.com/semantic-release/npm">@semantic-release/npm</a></li><li><a href="https://github.com/semantic-release/github">@semantic-release/github</a></li></ul><p>This means that if you have a bare-bones .releaserc.json file like this:</p><pre>{<br>	&quot;branches&quot;: [&quot;master&quot;]<br>}</pre><p>This is the equivalent of the following:</p><pre>{<br>  &quot;branches&quot;: [&quot;master&quot;],<br>	&quot;plugins&quot;: [<br>		&quot;@semantic-release/commit-analyzer&quot;,<br>		&quot;@semantic-release/release-notes-generator&quot;,<br>		&quot;@semantic-release/npm&quot;,<br>		&quot;@semantic-release/github&quot;<br>	]<br>}</pre><blockquote><strong><em>Note:</em></strong><em> the order of the plugins matters. They will be executed in the order that we have them in the plugins array.</em></blockquote><p>As you might’ve guessed, or might already know, it’s a bit complicated to figure out what the next version should judging by the commits. Hence this list of plugins.</p><p>Since I want to do a little extra like update the CHANGELOG file, I need some additional plugins, and since I’m not planning to publish an npm package, I removed the @semantic-release/npm plugin.</p><p>Specifying the &quot;plugins&quot; key in your configuration will overwrite the four default plugins, so you&#39;ll likely have to put some of them back in there if you&#39;re going to specify it and add your own configurations for one or more of the plugins.</p><p>In order to achieve the requirements I outlined above, I used the following semantic-release plugins:</p><ul><li><a href="https://github.com/semantic-release/commit-analyzer">@semantic-release/commit-analyzer</a></li><li><a href="https://github.com/semantic-release/release-notes-generator">@semantic-release/release-notes-generator</a></li><li><a href="https://github.com/semantic-release/changelog">@semantic-release/changelog</a></li><li><a href="https://github.com/semantic-release/github">@semantic-release/github</a></li><li><a href="https://github.com/semantic-release/git">@semantic-release/git</a></li></ul><p>Each of these plugins has its own GitHub repo and needs its own configuration. It sounds like kind of a lot, but it’s not that bad.</p><h3><a href="https://github.com/semantic-release/commit-analyzer">@semantic-release/commit-analyzer</a></h3><p>First, the commit-analyzer.</p><p>I needed to specify a &quot;preset&quot; and the &quot;releaseRules&quot; for that preset.</p><pre>{<br>    &quot;branch&quot;: &quot;master&quot;,<br>    &quot;plugins&quot;: [<br>        [<br>            &quot;@semantic-release/commit-analyzer&quot;,<br>            {<br>                &quot;preset&quot;: &quot;eslint&quot;,<br>                &quot;releaseRules&quot;: [<br>                    { &quot;tag&quot;: &quot;Breaking&quot;, &quot;release&quot;: &quot;major&quot; },<br>                    { &quot;tag&quot;: &quot;Build&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Chore&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Fix&quot;, &quot;release&quot;: &quot;patch&quot; },<br>                    { &quot;tag&quot;: &quot;New&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Update&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Upgrade&quot;, &quot;release&quot;: &quot;minor&quot; }<br>                ]<br>            }<br>        ],<br>        ...<br>    ]<br>}</pre><p>The eslint preset rules require a &quot;tag&quot; value to specify the word to look for in the commit message, and it has to be one of those 7-or-so title-cased words, according to the <a href="https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-eslint">README</a> for the eslint preset.</p><p>There’s actually one more for Docs which I did not include, and which you could include if you want.</p><h3><a href="https://github.com/semantic-release/release-notes-generator">@semantic-release/release-notes-generator</a></h3><p>This plugin is for generating the release notes content, and the configuration is exactly the same as the commit-analyzer.</p><pre>{<br>    &quot;branch&quot;: &quot;master&quot;,<br>    &quot;plugins&quot;: [<br>        ...<br>        [<br>            &quot;@semantic-release/release-notes-generator&quot;,<br>            {<br>                &quot;preset&quot;: &quot;eslint&quot;,<br>                &quot;releaseRules&quot;: [<br>                    { &quot;tag&quot;: &quot;Breaking&quot;, &quot;release&quot;: &quot;major&quot; },<br>                    { &quot;tag&quot;: &quot;Build&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Chore&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Fix&quot;, &quot;release&quot;: &quot;patch&quot; },<br>                    { &quot;tag&quot;: &quot;New&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Update&quot;, &quot;release&quot;: &quot;minor&quot; },<br>                    { &quot;tag&quot;: &quot;Upgrade&quot;, &quot;release&quot;: &quot;minor&quot; }<br>                ]<br>            }<br>        ],<br>        ...<br>    ]<br>}</pre><h3><a href="https://github.com/semantic-release/changelog">@semantic-release/changelog</a></h3><p>This plugin is for updating the CHANGELOG.md file with the release notes.</p><pre>{<br>    &quot;branch&quot;: &quot;master&quot;,<br>    &quot;plugins&quot;: [<br>        ...<br>        [<br>            &quot;@semantic-release/changelog&quot;,<br>            {<br>                &quot;changelogFile&quot;: &quot;CHANGELOG.md&quot;<br>            }<br>        ],<br>        ...<br>    ]<br>}</pre><blockquote><strong><em>Note:</em></strong><em> the value for changelogFile is a path to the file which will contain the release notes, which by convention is the </em><a href="http://changelog.md/"><em>CHANGELOG.md</em></a><em> file.</em></blockquote><h3><a href="https://github.com/semantic-release/github">@semantic-release/github</a></h3><p>This plugin is for creating the GitHub “Release.”</p><pre>{<br>    &quot;branch&quot;: &quot;master&quot;,<br>    &quot;plugins&quot;: [<br>        ...<br>        &quot;@semantic-release/github&quot;,<br>        ...<br>    ]<br>}</pre><p>I didn’t need to add any configuration for this one, so it can simply be added to the &quot;plugins&quot; array as a string, rather than a list.</p><h3><a href="https://github.com/semantic-release/git">@semantic-release/git</a></h3><p>This plugin is needed to add a release commit for the changes to the <a href="http://changelog.md/">CHANGELOG.md</a> file.</p><pre>{<br>    &quot;branch&quot;: &quot;master&quot;,<br>    &quot;plugins&quot;: [<br>        ...<br>        [<br>            &quot;@semantic-release/git&quot;, {<br>                &quot;assets&quot;: [&quot;package.json&quot;, &quot;CHANGELOG.md&quot;],<br>                &quot;message&quot;: &quot;chore(release): ${nextRelease.version} [skip ci]\\\\n\\\\n${nextRelease.notes}&quot;<br>            }<br>        ]<br>        ...<br>    ]<br>}</pre><p>I also included the &quot;package.json&quot; file hoping that its version would also be updated, but no dice. If anyone knows why that is, hit me up! Lol.</p><h3>GitHub Actions</h3><p>Phew! 😅</p><p>That should explain all the configuration. Now for the GitHub Actions release job!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*sY65GmgmcuhrCcm7y9QKLg.png" /></figure><p>The steps on the marketplace page <em>Usage</em> section for the Semantic Release Action are pretty straightforward and they seem to work.</p><ol><li>Add semantic-release configuration either to your package.json or a .releaserc.json file</li><li>Make sure you have the required auth tokens accessible as environment variables. For my purposes, since I’m not publishing an NPM package, I only need the GITHUB_TOKEN which is already exposed to GitHub Actions workflows via ${{ secrets.GITHUB_TOKEN }}</li><li>Create a GitHub Actions workflow yaml file in your repository. The example has the following:</li></ol><pre>steps:<br>  - name: Checkout<br>    uses: actions/checkout@v2<br>  - name: Semantic Release<br>    uses: cycjimmy/semantic-release-action@v2<br>    env:<br>      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}<br>      NPM_TOKEN: ${{ secrets.NPM_TOKEN }}</pre><p>Since we are not using the default plugins, we need to update this a bit to the one from the beginning.</p><pre>name: Release<br>on:<br>  push:<br>    branches: [ master ]</pre><pre>jobs:<br>  release:<br>    runs-on: ubuntu-latest</pre><pre>    steps:<br>        - name: Checkout<br>          uses: actions/checkout@v2</pre><pre>        - name: Semantic Release<br>          uses: cycjimmy/semantic-release-action@v2<br>          id: semantic<br>          with:<br>            extra_plugins: |<br>              @semantic-release/changelog<br>              @semantic-release/git<br>              conventional-changelog-eslint<br>          env:<br>            GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}</pre><p>The only difference here is that I’ve included the rest of the workflow definition at the top (you cannot just create a file with steps, but I imagine if you’re here, you likely already know that).</p><p>But more importantly, I added the with keyword with the extra_plugins to list the non-default plugins I&#39;ve configured in the .releaserc.json.</p><p>This is a feature of the <em>Semantic Release Action</em> GitHub Action.</p><p>Also worth noting is that I didn’t include the NPM_TOKEN variable in then env values since I&#39;m not publishing an NPM package.</p><p>And… that’s about it! ✨</p><p>This GitHub Action is awesome because it does all the work. We don’t have to even include <em>semantic-release</em> as a dependency, or write any custom jobs that run semantic-release to do the versioning. The GitHub action just needs our configuration and then says, “I’ll take it from here.”</p><h3>Links</h3><ul><li><a href="https://semantic-release.gitbook.io/semantic-release/usage/configuration">Semantic Release — Usage — Configuration</a></li><li><a href="https://github.com/marketplace/actions/action-for-semantic-release">Action For Semantic Release — GitHub Marketplace</a></li><li><a href="https://github.com/semantic-release/commit-analyzer">@semantic-release/commit-analyzer</a></li><li><a href="https://github.com/semantic-release/release-notes-generator">@semantic-release/release-notes-generator</a></li><li><a href="https://github.com/semantic-release/changelog">@semantic-release/changelog</a></li><li><a href="https://github.com/semantic-release/github">@semantic-release/github</a></li><li><a href="https://github.com/semantic-release/git">@semantic-release/git</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d589aba7e628" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ramojol/versioning-with-semantic-release-d589aba7e628">Versioning with semantic-release</a> was originally published in <a href="https://medium.com/ramojol">ramosly | blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should you use QA Wolf?]]></title>
            <link>https://medium.com/ramojol/should-you-use-qa-wolf-c22372e6c74a?source=rss----d27fe4c47e7c---4</link>
            <guid isPermaLink="false">https://medium.com/p/c22372e6c74a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[quality-engineering]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[qa-wolf]]></category>
            <dc:creator><![CDATA[Joel Ramos]]></dc:creator>
            <pubDate>Fri, 21 Aug 2020 18:22:36 GMT</pubDate>
            <atom:updated>2020-10-12T18:08:29.843Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently a client asked me if I had heard of the QA Wolf test automation framework.</p><p>I said, “No 🤔”</p><p>So, naturally, I decided to take a peek at it and take it for a spin. What follows will be a sort of play-by-play of what it was like for me (a QA engineer) to get up and running, along with its included GitHub Actions workflow for continuous integration (CI).</p><p>So let’s get started! 🚀</p><h3>Setting up</h3><p>I’m using an existing project, spacex-ships.</p><p>I’ll create a branch for qawolf</p><pre>git checkout -b qawolf</pre><p>Add qawolf per the documentation</p><pre>yarn create qawolf</pre><p>I’m also interested in testing out the Github Actions, so I answered “yes” to the CI question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pv4xlxDW_CshiSGLdwkgcQ.png" /></figure><p>The docs also say to verify the installation by running the howl command.</p><pre>npx qawolf howl</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*H6nl3ksZr8UMg68R-EXr_g.png" /></figure><p>Lol ✨</p><h3>Creating a test</h3><p>The docs then say to run the create command and pass a url, and the name of a test 🤔</p><p>Interesting.</p><p>Okay… here we go!</p><pre>npx qawolf create https://spacex-ships.now.sh navigation</pre><p>Running this command opened my default browser (chrome) to my site, evidently created some test code files, and printed out some options to the terminal. See below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFqDyguk904U7TXx0XMitA.png" /></figure><p>At this point, I haven’t touched anything in the browser yet. I notice that in the terminal it looks like we have options to tell QA Wolf to save, open a REPL (which is the node interpreter for executing JavaScript, which stands for Read Eval Print Loop).</p><p>So now, I’m going to scroll to the bottom and click on the Page 2 button to go to the next page and see what QA Wolf does.</p><p>After that, I choose the <em>Save and exit</em> option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqJTfPKoWYiJM0c0rPbu3w.png" /></figure><p>I guess my “navigation” test has passed haha.</p><p>I wonder what the code looks like 🤔</p><h3>First, the test code</h3><p>Interesting. Since QA Wolf is based on playwright, the code looks a lot like puppeteer code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTDLvgmEvNbMFfrNIV9A5Q.png" /></figure><p>This is pretty cool. If we were to continue doing things this way, we would probably have to start parameterizing and centrally locating configuration things like the url, locators, etc. That way, if they change we change them in one place.</p><p>I also notice that there’s no assertion. I suppose that’s not the end of the world. QA Wolf did a bit of the work for us. I’m also curious what happens if I create another test with the same name, do I get a new test in the same file? And what if I used a different url? 🤔</p><p>But before we get too far with this line of reasoning, let’s first look at the other files that were created, and we can come back to these.</p><p>A qawolf.config.js file <em>was</em> created, so let’s take a look at what’s in there 👀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*yrIm9LR14UH-antSO_sGCQ.png" /></figure><p>Okay this looks mostly like just QA Wolf stuff, but perhaps we can add arbitrary values and retrieve them in tests. Otherwise we can just create our own pattern for configuration, so not a big deal.</p><p>Onward!</p><h3>CI — Github Actions</h3><p>So, I answered “yes” to the CI question when I installed QA Wolf. Naturally, a .github folder was created in the root of my directory.</p><p>In this directory a workflows directory was created with a qawolf.yml</p><p>GitHub knows to look for yaml files in the .github/workflows folder when changes are pushed. See below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSTKwLI-8LN6BE5tvY7r5g.png" /></figure><p>The on: key, or field, defines the GitHub events that trigger the workflow. It looks like they&#39;ve added a trigger for pushevents on all git branches. You actually don&#39;t need to include the branches: * part, but I imagine it&#39;s included to let you know know that you can limit to only certain branches.</p><p>Anyway, with this workflow as it is, my test should run in a GitHub runner as soon as I push my branch.</p><p>It also looks like there’s a step for uploading artifacts. Are we going to get a report when the tests run? 🤔</p><p>Let’s try it and see!</p><pre>git add .github/ .qawolf/ qawolf.config.js package.json yarn.lock<br>git commit -m &quot;add qawolf test and github actions workflow&quot;<br>git push -u origin qawolf</pre><p>Now let’s go to GitHub and to the Actions tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SwhKgHzmYPi7VIoZRwdlrA.png" /></figure><p>Heyyy it’s running! 🚀</p><p>Let’s click on the workflow name with the yellow spinning circle to see the job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnAiOhQTfUeXEk1k_FWCqg.png" /></figure><p>Nice.</p><p>Now once the job finishes let’s expand the step that runs the tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7mtbtrBatwBc4UOrQNTfQ.png" /></figure><p>Okay cool cool 🤔</p><p>Looks like artifacts were uploaded, and we have a <strong>1</strong> in the upper-right corner. “Artifacts” are files that are produced by the job that you want GitHub to keep rather than discard when the job has completed.</p><p>So let’s see what we got!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*zTvkVXjihhId_ZfZT-Zf2A.png" /></figure><p>Interesting. A video and a text log.</p><h3>Contents of the text log</h3><pre>debug: ignore non-wheel s:croll event {&quot;isTrusted&quot;:true}<br>debug: ignore non-wheel s:croll event {&quot;isTrusted&quot;:true}<br>debug: ignore non-wheel s:croll event {&quot;isTrusted&quot;:true}<br>debug: ignore non-wheel s:croll event {&quot;isTrusted&quot;:true}<br>debug: qawolf: get clickable ancestor for //*[@id=&#39;root&#39;]/div/div[3]/div/div[12]/div/a[3]<br>debug: qawolf: found clickable ancestor: A //*[@id=&#39;root&#39;]/div/div[3]/div/div[12]/div/a[3]<br>debug: qawolf: get clickable ancestor for //*[@id=&#39;root&#39;]/div/div[3]/div/div[12]/div/a[3]<br>debug: qawolf: found clickable ancestor: A //*[@id=&#39;root&#39;]/div/div[3]/div/div[12]/div/a[3]<br>log: 2<br>debug: ignore non-wheel s:croll event {&quot;isTrusted&quot;:true}</pre><p>And then the video looks… weird. It’s 5 seconds long, and it looks like it waits for the page to load and then ends. It looks like we did not actually get to page 2 judging by the page number at the bottom.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNPEs2F8lKSk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNPEs2F8lKSk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNPEs2F8lKSk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/80a5bb56d5f3dc04ecf38a5bdd771a0a/href">https://medium.com/media/80a5bb56d5f3dc04ecf38a5bdd771a0a/href</a></iframe><p>Looking back at the generated test code, I suspect that the click happens, the scroll happens, but we don’t wait for the page to actually navigate before continuing or calling the test “done.”</p><p>We can run the test locally and see what happens.</p><pre>npx qawolf test navigation</pre><blockquote><em>Maybe we should have done that before jumping to seeing CI run, but whatever. I was eager haha.</em></blockquote><p>Anyway, as I suspected I think we need to tell playwright to wait for the page to navigate to page 2.</p><p>Often times on most websites you can use await page.waitForNavigation() to tell playwright / puppeteer to wait for the next page to load. Since my app is a single-page app we&#39;re not actually changing the url or navigating to a new page, let&#39;s just wait for the first ship to appear on the next page and then verify the name of this ship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*lpVCVbnjjFwZYpLYJoEGGA.png" /></figure><p>Now let’s run the test again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*eogH3ZA3kORXhzmgt-yLnA.png" /></figure><p>Nice.</p><p>Alright let’s push and see it run in CI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ew5MiJT106Zile3T2mj-pQ.png" /></figure><p>Wow. Okay the video is only 2 seconds long this time 🤔</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXs6aCM5cog4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXs6aCM5cog4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXs6aCM5cog4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/21da761cb52b611a47ff373ca6d01121/href">https://medium.com/media/21da761cb52b611a47ff373ca6d01121/href</a></iframe><p>Welp… maybe the video feature needs work. Or maybe I’m doing something wrong 🤷‍♂️</p><p>Let’s move on…</p><p>Evidently, we can tell QA Wolf to prefer certain html attributes when locating elements. A best practice is to use a dedicated html attribute for locators. The documentation shows data-qa attributes in their examples. My site has data-tid attributes. Let&#39;s try updating the qawolf.config.js file and recreate the test to see what happens.</p><p>We can add a comma-separated list of these attributes to prefer to an attribute field in the qawolf.config.js file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*EHRojo35yFXKwFup1bqtVg.png" /></figure><p>Aaaaannnnd looks like that works!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_E_dAluT-WjgPF1xuD9LDA.png" /></figure><h3>createTemplate 👀</h3><p>Thiiiiiiiis feature looks interesting. You can actually customize the test code that is generated when you run npx qawolf create [&lt;https://someurl.com&gt;](&lt;https://someurl.com&gt;) testname</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HumSWpHbtat3ccUSLbgz1Q.png" /></figure><p>Perhaps we could use this to feature to always use process.env.BASE_URL to grab the url from configuration rather than passing in a url to hardcode into each test.</p><p>This is preferable for running tests against different environments. Maybe I want to run the GitHub Actions workflow against staging first, and then against production after release. Best not to hardcode the url into the test.</p><p>Let’s update the GitHub Actions workflow to create one job per browser.</p><h3>GitHub Actions CI — Browser Matrix</h3><p>QA Wolf has an --all-browsers command line option, but I actually prefer having a job per browser so that we can see the chromium job fail, or the firefox job fail, etc.</p><p>GitHub Actions workflow syntax supports this. We can add a strategy.matrix value with a named list, and GitHub will create a job per item in the list.</p><p>We’ll call our list browser and parameterize the job name, the artifacts name, and the QAW_BROWSER value.</p><p>I’m also going to do this directly in GitHub since their editor has autocompletion, which is nice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mn5Yxd10mf1Uj-tg_MZFNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5UHslaACYELaKUxYrbGTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TnltcCD8pW4AbaittGyVww.png" /></figure><p>When we commit changes to our branch, we can click the Actions tab and we should see 3 jobs running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5ozDAzrD2gEVyHSK1i4KQ.png" /></figure><p>Nice.</p><p>And at the end, we should have our 3 named artifacts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgN67bK2npwlGPBA4i6XSQ.png" /></figure><h3>Conclusion</h3><p><strong>It’s neat</strong> ✨</p><p>This is pretty neat to get up and running, quickly. It’s especially cool for folks who might be new to JavaScript and who can learn from reviewing the code that is generated.</p><p>For someone like me who has to create/maintain test frameworks, I’d be curious what maintaining something like this would be like. Perhaps combining the custom templates with some organization for localization, desktop/mobile locators, and reporting on results, it could be doable 🤔</p><p>It also looks like there are some requested enhancements for supporting the browser’s back/forward buttons, file uploads and downloads, drag &amp; drop, and iframes.</p><p>Playwright supports these, but QA Wolf just can’t generate tests with playwright code for these behaviors.</p><p><strong>It doesn’t solve all automation challenges</strong></p><p>Overall, I think you would still end up needing to build some framework-y patterns for parameterizing which environment you’re hitting, localization for different languages, or perhaps a visual-regression tool for comparing screenshots, centralizing logic, etc.</p><p>For example, when a page’s logic or workflow changes, you can “Edit” an existing test and rerecord an update to that test. But if we don’t build in our own reusable logic for common page interactions it seems we’d have to do a lot rerecording, especially if you have a lot of tests.</p><p>One of the things we do in test frameworks is separate page interactions from the logic of tests. We create an abstraction layer that wraps whatever tool we’re using for page interactions (E.g., WebDriver, Puppeteer, Playwright, Appium, etc), and then we reference that layer to make reusable step functions which are implemented in tests.</p><p>The benefit of this approach is that when things change on the page, we can go to the logic in the page-interaction layer and effectively “swap out a part.” Generally the Page Object Model is used to centralize the page interactions where classes are created to model pages and components. It clarifies where to put logic and is a helpful mental model.</p><p>So how does QA Wolf solve this problem? Or, is it even trying to solve this problem?</p><p>Maybe QA Wolf is saying that we <em>shouldn’t</em> care about this much architecture. Maybe they’re saying, “just get scripts created and running and don’t waste your time.”</p><p>Even if we go along with that, QA Wolf is only coding the behaviors; it cannot add the assertions. So, if it’s critical that a piece of legal text is on the page, you’re gonna have to add an assertion into the code that QA Wolf generates, or have a visual-regression check that screenshots the page and compares to a baseline image. Both of those you’ll have to add yourself.</p><p>Similarly, if you have a bunch of tests and a lot of them fail, they all have to be updated. With the page object model, you often times can update a single centralized locator or page interaction, and update all the tests that broke which were relying on it.</p><p>This suggests to me that you’re making a trade-off between the speed of getting tests created and the ease of maintenance.</p><p>But who knows!? Maybe a large project somewhere will produce a pattern for leveraging QA Wolf’s strengths while minimizing the maintenance burden.</p><p>If you’ve been using it on a project, I’d be curious to hear how it’s going and if you’ve run into maintenance challenges, or if it turned out to be easier to just delete outdated tests and record new ones.</p><p>Anyway, that’s all for now! 🍻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c22372e6c74a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ramojol/should-you-use-qa-wolf-c22372e6c74a">Should you use QA Wolf?</a> was originally published in <a href="https://medium.com/ramojol">ramosly | blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Testing in 2020 with k6!]]></title>
            <link>https://medium.com/ramojol/load-testing-in-2020-with-k6-e43c13c5f403?source=rss----d27fe4c47e7c---4</link>
            <guid isPermaLink="false">https://medium.com/p/e43c13c5f403</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[stress-testing]]></category>
            <dc:creator><![CDATA[Joel Ramos]]></dc:creator>
            <pubDate>Fri, 07 Aug 2020 21:52:48 GMT</pubDate>
            <atom:updated>2020-07-15T15:48:14.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PPablta9dVZ-Dlc10hrExg.png" /></figure><p>I was recently looking into the options for load testing tools.</p><p>On a previous project we had used Gatling, in which you write your tests in Scala. That worked well, and the reports were good, but now that I’m on a new team, I wanted to see what was out there.</p><p>And I was looking for something with which we could write tests in a more familiar language.</p><p>The tools I came across were these:</p><ul><li><a href="https://gatling.io/">Gatling</a> — Scala</li><li><a href="https://locust.io/">Locust.io</a> — Python</li><li><a href="https://github.com/tsenart/vegeta">Vegeta</a> — Go</li><li><a href="https://k6.io/">k6</a> — JavaScript</li></ul><p>It was doubtful anyone on the team was gonna be familiar with Scala, nor am I a big Scala user. Python is probably the language I know the best, but only QAs use it here. The front-end folks all know JavaScript, and the API folks use Go, which pushed me more towards k6 and Vegeta.</p><p>All of these are open source by the way, and some have enterprise solutions.</p><p>Vegeta looked like it would get the job done. It’s basically a github repo with a README and some instructions on how to install it, run it, etc.</p><p>k6 looked much more polished/full-featured. You write tests in JavaScript, it’s console output is clean, and it can output to DataDog, Kafka, and more.</p><p>Since k6 just looked friendlier to use, and I’m more familiar with JavaScript anyway, I decided to give it a whirl!</p><h3>Taking k6 for a spin</h3><p>If you’re on a Mac, you can just brew install k6</p><p>Sweet.</p><p>They also have a docker image which is also cool, but I went with brew for now.</p><p>I created a folder named k6 on my computer.</p><p>I created a script.js file and followed the documentation to get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*t0ATI-vos-RgDz2cRX9PEQ.png" /></figure><p>You might notice that I have a package.json file. I ran yarn init to initialize my project here expecting that I would have to install packages. But evidently, brew-installing k6 was enough and these imports worked 🤷‍♂️</p><blockquote><em>more on this later 👀</em></blockquote><p>Anyway…</p><p>Now that I had created the script.js file, all I had to do was run it.</p><pre>$ k6 run script.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*PR_MK0WtGsN_2Tj-4yx6jw.png" /></figure><p>Here, you can see that vus (virtual users) is 1 by default, as is vus_max.</p><p>If we want to up those numbers, we can pass them as options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*Bw4XAbzcBnJv6PUh8-dGaQ.png" /></figure><p>This time, I had k6 run with 10 virtual users, and hit the server for 30 seconds.</p><h3><a href="http://test.k6.io/">test.k6.io</a></h3><p>You probably noticed that the script is hitting <a href="http://test.k6.io/">test.k6.io</a>.</p><p>That’s <em>another</em> cool thing about k6 is that they have a test environment for you to run tests against. If you navigate to <a href="http://test.k6.io/">http://test.k6.io</a> you’ll see other urls they have that you can hit to test different things 🤯</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXrK-WKQGXTxUAkp-jge3Q.png" /></figure><h3>Assertions or “checks”</h3><p>Next task was to add a check to verify that we get a 200 response from the server.</p><p>Enter script2.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*C0UC9ae3Knn2FOypGdTvQQ.png" /></figure><ol><li>I added the comments which were in the documentation. Evidently, setup code should live outside the default function. Virtual user code should live <em>inside</em> the default function.</li><li>In addition to importing the sleep function from k6, I&#39;ve imported the check function. Then, rather than discarding the response form http.get() it is stored in a res variable, passed to check() where its status is compared to 200</li></ol><p>And now, when I run script2.js</p><pre>k6 run --vus 10 --duration 30s script2.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*8ayQ3QrnojeRI2Wznf0whQ.png" /></figure><p>🎉</p><p>This is awesome!</p><p>And the documentation keeps going. They distinguish between load tests and stress tests. They go over how to ramp up the load over time, hold the load steady, and then ramp down.</p><p>I think the k6 folks did such a good job with the experience of not just using the tool, but also following their documentation and interacting with their test environment, that I actually <em>want</em> to load test and play k6 more.</p><h3>Caveats</h3><p>The k6 docs note two trade-offs of using k6 in the <a href="https://k6.io/docs/#what-k6-does-not">What k6 does not</a> section.</p><ol><li>The first is that it does not run in a browser and so, “does not render webpages the same way a browser does.” So you might get misleading results if you are hitting urls for webpages rather than hitting API endpoints.</li><li>The second is that it does not run in Node, which was eluded to in the beginning. Since it’s actually written in Go but just letting you write scripts in JavaScript, there are extra steps you’d have to do in order to import external modules.</li></ol><p>And #2 explains why I didn’t need to yarn add any npm packages.</p><p>And they have VS Code extensions?!</p><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=k6.k6">k6 for Visual Studio Code</a></li></ul><p>And they have TypeScript types, in which case you <em>would</em> use yarn or npm to initialize the project with a package.json file and then install @types/k6 to get the intellisense in VS Code.</p><p>I’m curious if anyone else out there has been using it and has come across any other gotchas.</p><p>But anyway, for load and stress testing (in non-production environments!) I think this k6 tool looks super cool!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e43c13c5f403" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ramojol/load-testing-in-2020-with-k6-e43c13c5f403">Load Testing in 2020 with k6!</a> was originally published in <a href="https://medium.com/ramojol">ramosly | blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controlling How Docker Compose Exits]]></title>
            <link>https://medium.com/ramojol/controlling-how-docker-compose-exits-da17c000d0be?source=rss----d27fe4c47e7c---4</link>
            <guid isPermaLink="false">https://medium.com/p/da17c000d0be</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Joel Ramos]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 16:14:54 GMT</pubDate>
            <atom:updated>2020-06-22T16:14:15.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pxI1WKj6B3F_7QhTF9sM-Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@marcuslenk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Marcus Lenk</a> on <a href="https://medium.com/s/photos/shipping-container-blue?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>What follows will be a description of a small docker-compose challenge I had recently.</p><ul><li>I needed two services in the compose file. The first service is long-running, the other runs and exits.</li><li>I wanted to run docker-compose up, spin up the long-running service, then run the second service which requires the first, then tear everything down.</li><li>I also wanted the run-and-exit service to build a new image each time when there were changes.</li></ul><h3>First Attempt</h3><p>The point of this file was to run UI tests in a browser. Since getting all the requirements for running a browser in a container is painful, and since SeleniumHQ has already done the work of making node container images for this purpose, running this image separately made the most sense, especially since it would allow me to swap in a different image for a different browser later.</p><p>So, I created my docker-compose.yml file with one service for the browser image, and the other for my tests.</p><pre>version: &#39;3.7&#39;<br>services:<br>  selenium:<br>    container_name: selenium<br>    environment:<br>      - CHROME_VERSION=83.0.0<br>      - NO_PROXY=127.0.0.1,localhost,.domain.tld<br>      - START_XVFB=false<br>    healthcheck:<br>      interval: 15s<br>      retries: 3<br>      timeout: 30s<br>      test: &quot;/opt/bin/check-grid.sh --host selenium --port 4444&quot;<br>    image: selenium/standalone-chrome:3.141.59-selenium<br>    ports:<br>      - &quot;4444:4444&quot;<br>    logging:<br>      driver: &quot;none&quot;</pre><pre>  test:<br>    container_name: test<br>    build:<br>      context: .<br>      args:<br>        - NPM_AUTH_TOKEN<br>    env_file:<br>      - .env<br>    environment:<br>      - SELENIUM_HOST=selenium<br>      - SELENIUM_PATH=/wd/hub<br>      - SELENIUM_PORT=4444<br>    depends_on:<br>      - selenium</pre><p>Then I ran docker-compose up</p><h3>Result</h3><p>The test container image built from the Dockerfile in the local directory, the tests ran, and then the terminal just hung there after requiring me to CTRL-C out.</p><p>I realized that this was because the long-running browser container was just hanging out, waiting to receive more requests.</p><h3>Second attempt</h3><p>So I did some googling, and came across a couple command-line options for docker-compose that I was not aware of.</p><ul><li>--abort-on-container-exit : tells docker-compose to exit when a container exits</li><li>--exit-code-from &lt;service_name&gt; : tells docker-compose from which container to use the exit code</li></ul><p>Sweet!</p><p>So in my case, this turns my compose command into something like</p><pre>docker-compose up \<br>--abort-on-container-exit \<br>--exit-code-from test</pre><p>So now when I run this command:</p><ul><li>The selenium container starts up first</li><li>The test container runs and exits</li><li>When the test container exits, the selenium container is stopped</li><li>docker compose exits 🎉</li></ul><blockquote><em>Note that “test” is the name of the service from the compose file, and not the container_name value from the compose file, which I happened to give the same name. … sorry 😬</em></blockquote><h3>One more thing…</h3><p>docker-compose doesn’t build on each run.</p><p>What do I mean by that?</p><p>So, in my case, I have a Dockerfile in the root of the project, so instead of specifying an image for the test service, I had build: . instead thinking that each time I run docker-compose up it would build a new image before running.</p><p>I was wrong…</p><p><a href="https://github.com/docker/compose/issues/1487">docker-compose up doesn&#39;t rebuild image although Dockerfile has changed · Issue #1487 · docker/compose</a></p><p>It turns out that using the build: . field in the docker-compose.yml file will cause the container to build the first time, but not subsequently, even after changes are made to the Dockerfile, or files in the repository.</p><p>In order to force the rebuild, you can run docker-compose build &amp;&amp; docker-compose up</p><h3>What I ended up with</h3><p>After all that, I ended up with this:</p><pre>docker-compose build &amp;&amp; \<br>docker-compose up \<br>--abort-on-container-exit \<br>--exit-code-from test &amp;&amp; \<br>docker-compose down</pre><p>I tacked on docker-compose down at the end to tear down the default network and other stuff that compose creates to run the containers.</p><p>I’ll probably end up putting this in a shell script so that I don’t have to search my history to find this longer command each time I want to run it, or worse, type the whole thing out.</p><p>But, that’s it! This would be useful anytime you have a container running as a command that depends on another running container. I was glad to find that compose had solutions to my problem. Hopefully this helps someone else out there 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da17c000d0be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ramojol/controlling-how-docker-compose-exits-da17c000d0be">Controlling How Docker Compose Exits</a> was originally published in <a href="https://medium.com/ramojol">ramosly | blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MacBooks, Typescript, ZSH, Oh my!]]></title>
            <link>https://medium.com/ramojol/macbooks-typescript-zsh-oh-my-203b822ef5e6?source=rss----d27fe4c47e7c---4</link>
            <guid isPermaLink="false">https://medium.com/p/203b822ef5e6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[zsh]]></category>
            <category><![CDATA[tsc]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joel Ramos]]></dc:creator>
            <pubDate>Mon, 25 May 2020 00:46:35 GMT</pubDate>
            <atom:updated>2020-05-24T22:18:55.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Photo of three balls of yarn… cuz ya know, this post will be talking about yarn." src="https://cdn-images-1.medium.com/max/1024/1*lFeiRevUOAiG44Oxcp4yEw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@taradee?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tara Evans</a> on <a href="https://unsplash.com/s/photos/yarn?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I was setting up a typescript project for learning purposes, and noticed that ZSH was complaining that the tsc command was not found.</p><figure><img alt="Screenshot of my terminal and the “command not found” error message after running tsc" src="https://cdn-images-1.medium.com/max/1024/1*rcCfRAJl5ax6Jbd2aPDxig.png" /></figure><p>🌎 I tried installing globally with yarn, but no dice.</p><p>Most of what I was finding online was saying to install globally with npm but in an effort not to mix yarn and npm I was stubbornly avoiding npm.</p><p>I figured my .zshrc must be missing some PATH directory or something that my .bashrc file has, which I figured I’d look into it later.</p><p>Also, npx tsc worked, but tsc did not. So, okay fine that works but it still bugged me that plain ol’ tsc didn’t work.</p><h3>brew</h3><p>Eventually after some googling I came across this <a href="https://stackoverflow.com/a/61360373">StackOverflow answer</a> that mentioned installing typescript with brew. I had installed typescript in the project, but I hadn’t considered installing it with brew given that I had tried installing with yarn globally.</p><p>Sure enough, after running brew install typescript I am now able to run tsc from anywhere.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXHU4ipkOAGaQDejEUZ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Freaction-XHU4ipkOAGaQDejEUZ&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FXHU4ipkOAGaQDejEUZ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/362cfbf5f1724e39f312f457a5f341ad/href">https://medium.com/media/362cfbf5f1724e39f312f457a5f341ad/href</a></iframe><p>And this makes sense since brew manages all the files and symlinks for the things that it installs. I generally just think of brew as the package manager for Mac OS things, and not necessarily for Node or JavaScript-library things.</p><p>I also was still not sure why installing globally with yarn did not work. I imagined yarn would do something similar in order to make things accessible from anywhere, but then again if it puts things in a folder that’s not in the PATH then it ain’t gonna work.</p><h3>npm</h3><p>Then I wondered if installing globally with npm would work as the more highly-voted answers on that same StackOverflow post suggested. So I figured I’d try it 🤷‍♂</p><p>First, I needed to uninstall the typescript I had installed with brew.</p><pre>➜  nightwatch-ts git:(master) ✗ <strong>brew uninstall typescript</strong><br>Uninstalling /usr/local/Cellar/typescript/3.9.3... (180 files, 51.7MB)<br>➜  nightwatch-ts git:(master) ✗ <strong>tsc</strong>                                                                                 <br><strong>zsh: command not found: tsc</strong></pre><p>Then I needed to install globally with npm…</p><pre>➜  nightwatch-ts git:(master) ✗ <strong>npm i typescript -g</strong><br>/Users/joel/npm/bin/tsc -&gt; /Users/joel/npm/lib/node_modules/typescript/bin/tsc<br>/Users/joel/npm/bin/tsserver -&gt; /Users/joel/npm/lib/node_modules/typescript/bin/tsserver<br>+ typescript@3.9.3<br>added 1 package from 1 contributor in 2.37s</pre><pre>➜  nightwatch-ts git:(master) ✗ <strong>tsc --version</strong><br><strong>Version 3.9.3</strong></pre><p>Unbelievable 😤</p><h3>yarn</h3><p>So then I’m like, “yarn, what gives?”</p><p>I google the yarn docs. Maybe I installed typescript incorrectly the first time (probably lol).</p><figure><img alt="Screenshot of documentation for `yarn global` command" src="https://cdn-images-1.medium.com/max/1024/1*6zuXNxPKSs3wObk6CLvSpw.png" /></figure><p>Welp, I’m not sure what I did the first time but I definitely did not do it the way the documentation suggests. I probably did a yarn add typescript -g something-or-other. Serves me right.</p><p>So I uninstalled the globally-installed typescript that I had just installed with npm.</p><pre>➜  nightwatch-ts git:(master) ✗ <strong>npm uninstall typescript -g</strong><br>removed 1 package in 0.132s</pre><p>Then tried with yarn (but this time the way the documentation suggests).</p><pre>➜  nightwatch-ts git:(master) ✗ <strong>yarn global add typescript</strong><br>yarn global v1.22.4<br>[1/4] 🔍  Resolving packages...<br>[2/4] 🚚  Fetching packages...<br>[3/4] 🔗  Linking dependencies...<br>[4/4] 🔨  Building fresh packages...</pre><pre>success Installed &quot;typescript@3.9.3&quot; with binaries:<br>      - tsc<br>      - tsserver<br>✨  Done in 3.55s.</pre><p>Moment of truth!</p><pre>➜  nightwatch-ts git:(master) ✗ <strong>tsc --version</strong><br><strong>Version 3.9.3</strong></pre><p>Unbelievable 🤦‍♂</p><p>This was probably the longest possible route to get here, but heyyyy we made it! 😅</p><p>At the end of the day, there are three ways to install typescript globally that make the tsc command available from anywhere:</p><ol><li>brew install typescript</li><li>npm i typescript -g</li><li>yarn global add typescript</li></ol><p>Also interesting is npm and yarn both have commands to find where each puts global things.</p><p>For npm:</p><pre>➜  nightwatch-ts git:(master) ✗ <strong>npm config get prefix</strong><br>/Users/joel/npm</pre><p>For yarn:</p><pre>➜  nightwatch-ts git:(master) ✗ <strong>yarn global bin</strong><br>/Users/joel/npm/bin</pre><p>Hmmmmmmm… 🤔 INTERESTING!</p><p>What’s in there? 👀</p><p>If I cd into that ~/npm folder, and list the contents with ls I only see four folders:</p><ul><li>bin</li><li>etc</li><li>lib</li><li>share</li></ul><p>And then if I list the contents of ~/npm/bin I can see all the globally-installed commands like jest and create-react-app, one of which is tsc.</p><p>So it looks like both npm and yarn install things in 👏 the 👏 same 👏 place 👏 (when installing globally).</p><p>🐰 🕳</p><p>Anyway, putting this here in case anyone else runs into this and wants to cut to the chase 🍻</p><h3>Links</h3><ul><li><a href="https://classic.yarnpkg.com/en/docs/cli/global/">https://classic.yarnpkg.com/en/docs/cli/global/</a></li><li><a href="https://docs.npmjs.com/misc/config#prefix">https://docs.npmjs.com/misc/config#prefix</a></li><li><a href="https://stackoverflow.com/questions/39404922/tsc-command-not-found-in-compiling-typescript">https://stackoverflow.com/questions/39404922/tsc-command-not-found-in-compiling-typescript</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=203b822ef5e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ramojol/macbooks-typescript-zsh-oh-my-203b822ef5e6">MacBooks, Typescript, ZSH, Oh my!</a> was originally published in <a href="https://medium.com/ramojol">ramosly | blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I’ve been Using Puppeteer]]></title>
            <link>https://medium.com/ramojol/how-ive-been-using-puppeteer-b8010e374ff7?source=rss----d27fe4c47e7c---4</link>
            <guid isPermaLink="false">https://medium.com/p/b8010e374ff7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Joel Ramos]]></dc:creator>
            <pubDate>Mon, 11 May 2020 15:31:01 GMT</pubDate>
            <atom:updated>2020-05-11T15:31:01.214Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey all 👋</p><p>Today I thought I would go over how I’ve been using Puppeteer’s… maybe less obvious features.</p><p>If you’ve made it here, you probably already know that <a href="https://developers.google.com/web/tools/puppeteer">Puppeteer is a Node JS library</a> for automating Chrome / Chromium. And I <em>do</em> use it to navigate to pages, click things, and take screenshots.</p><p>However!</p><p>Puppeteer gives you access to a lot more of the browser, like the console, the browser requests, redirect chains, the TLS certificate, etc. These are the Puppeteer powers I’ve been using more lately, rather than just to imitate user behaviors.</p><p>If you’re looking to get started with Puppeteer, maybe take a look at <a href="https://blog.ramosly.com/puppeteer-getting-into-coding-with-browser-automation-6d4ad1364a75">my other post</a>.</p><p>What follows will be more about looking under the hood of the browser and verifying that things are working as we expect.</p><h3>Under the Hood 🔧</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Sn0JtG0sesM63IrSlEosww.jpeg" /></figure><p>As I mentioned at the start, I find myself using Puppeteer for stuff that <a href="https://www.selenium.dev/documentation/en/webdriver/">Selenium WebDriver</a> can’t do.</p><p>For example, maybe we want to ensure that a certain response has a certain header when users navigate to a page.</p><p>Or, maybe you want to check that a page is rendered on the server, and so certain HTTP requests should <em>not</em> be present when you navigate directly to a url.</p><p>Accessing this information is relatively simple to do with Puppeteer, so let’s do it!</p><h3>Inspecting HTTP Responses 💌</h3><p>So there are actually two approaches to inspecting responses.</p><ol><li>You can grab the response from the call to page.goto() which is the return value. Then you can inspect that.</li><li>You can also intercept all the requests the browser makes as you navigate around. You can then use JavaScript logic to pluck out the ones you want, grab values from them, or return a mocked response instead, etc.</li></ol><p>The first one is simpler, so let’s start with that.</p><p>If we store the result of the call to page.goto() in a variable, we can access the functions of the Response object we got back.</p><pre>// index.js<br>...<br>// navigate to a page<br><strong>const response</strong> = await page.goto(&#39;https://www.google.com&#39;)<br>console.log(&#39;Response headers: &#39;, <strong>response.headers()</strong>)<br>...</pre><p>When you run the script with node index.js this time, you should see the response headers logged to the console.</p><figure><img alt="Gif of running the script and seeing the response headers get logged to the terminal" src="https://cdn-images-1.medium.com/max/1024/1*mATJzIOMtgfmxg4Kqr_DCA.gif" /><figcaption>Response headers logged to the console. (The “headless” option was removed for the gif so that the browser would not display).</figcaption></figure><p>🎉</p><blockquote><strong>Note:</strong> you could just make a request without a browser to inspect the response, but it can be useful to inspect the browser requests while a UI test runs.</blockquote><p>Now that we have access to the headers, we can verify things about the headers being returned in the response, or that the header value is one that we expect. And we don’t need any extra tools! 😅</p><p>Let’s look at how to do #2 now.</p><p>If the approach from #1 was like tossing a request to the server and catching the response, <em>this </em>approach is more like listening in on the browser’s conversation.</p><p>For #2, we need to tell Puppeteer that any time the Page gets a response from a request the webpage sent, we wanna know about it. So, we’ll add a call to page.on() and tell it we’re interested in responses.</p><p>Here’s the whole thing. Notes below.</p><pre>const puppeteer = require(&#39;puppeteer&#39;);</pre><pre>(async () =&gt; {</pre><pre>    // Puppeteer stuff<br>    const browser = await puppeteer.launch()<br>    try {<br>        const page = await browser.newPage()</pre><pre>        // create a string of repeating &#39;=&#39; equal signs<br>        // for separation when logging to the console<br><strong>        const separator = Array(156).join(&#39;=&#39;)</strong></pre><pre>        <strong>// Tell Puppeteer what to do with intercepted responses<br>        await page.on(&#39;response&#39;, async response =&gt; {<br>            // Ignore OPTIONS requests<br>            if(response.request().method() !== &#39;POST&#39;) return</strong></pre><pre><strong>            if (response.url().includes(&#39;/graphql&#39;)) {<br>                console.log(&#39;\n 🚀 We got one!: &#39;, response.url())<br>                const data = await response.json()<br>                console.log(separator)<br>                console.table(data.data.ships)<br>                console.log(&#39;\nHeaders: \n&#39;, response.headers())<br>                console.log()<br>                console.log(separator)<br>            }<br>        })</strong></pre><pre>        // navigate to a page<br><strong>        const pageUrl = &#39;</strong><a href="https://spacex-ships.now.sh&/#39;"><strong>https://spacex-ships.now.sh&#39;</strong></a><br>        await page.goto(<br>            <strong>pageUrl</strong>, {waitUntil: &#39;networkidle0&#39;}<br>        )</pre><pre>} finally {<br>        console.log(&#39;Closing the browser...&#39;)<br>        await browser.close()<br>    }<br>})();</pre><blockquote><strong>Note:</strong> for this example, I wasn’t sure about the ethical implications of hitting someone’s production website and logging out data from their website’s requests, so I ended up making a small react site using create-react-app that makes a single request for Ships from the SpaceX GraphQL API.</blockquote><blockquote>You can find the code for the SpaceX Ships site on GitLab: <a href="https://gitlab.com/joel.mariano.ramos/spacex-ships">https://gitlab.com/joel.mariano.ramos/spacex-ships</a></blockquote><p>Let’s take this apart and go through it:</p><ol><li>page.on() takes two parameters. The first is the name of the event to listen for. The second is the function you want to execute when the event occurs.<br>I.e., page.on(&#39;event to listen for&#39;, functionToCall(event)) <br>Thus, our version was more like this:<br>page.on(&#39;<strong>response</strong>&#39;, <strong>function(response) { // stuff }</strong> ) <br>We used the arrow-function syntax for the function, so: <br>page.on(&#39;response&#39;, <strong>response =&gt; { // stuff }</strong> ) <br>And then since we wanted to grab the data from the response, which is an asynchronous operation, we needed to use await. So our function also needed to be an async function. <br>page.on(&#39;response&#39;, <strong>async</strong> (response) =&gt; { <strong>await response.json()</strong> } )</li><li>I know my app makes a request to <a href="https://api.spacex.land/graphql/">https://api.spacex.land<strong>/graphql</strong>/</a> when the page loads. So inside of our “callback” function, I have a check to see, if(response.url().includes(&#39;<strong>/graphql</strong>&#39;)) and if so, grab the response data and log it. I also log the response headers, just to show that we can.</li><li>I’ve also passed the {waitUntil: ‘networkidle0’} options object to page.goto() to tell Puppeteer to wait for all the page requests to finish before continuing.</li></ol><p>Mid-way through all this I decided to start putting these examples in their own folders, lol. So I’m going to run this one with node example3/index.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51xMeDnRP4RbVifG5XJ11Q.gif" /></figure><p>As you can see, we used console.table() to log the Ships data returned by the SpaceX GraphQL API. The data is returned as JSON though, so each column is a field from the response that was returned.</p><p>The JSON for the first ship result from the API looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*vVbUM1yUydDe5kzX_Axbpg.png" /></figure><p>And we can see that this matches the first Ship displayed on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2uosFt-R3cSafayo4dlWA.png" /></figure><p>Inspecting outgoing requests is a similar process. Instead of listening for the &#39;response&#39; event, you listen for the &#39;request&#39; event in the page.on() function.</p><h3>Altering Outgoing Requests 🛠</h3><p>We can also add our own request headers to be sent with browser requests. This is useful if you need to pass feature flags, or certain headers to verify the right things are happening at edge servers, etc.</p><p>Note that there’s actually a page.setUserAgent() function specifically for setting the user-agent.</p><p>Here we’ll add the headers to the <em>Page</em> object and we’ll make sure to do so <em>before</em> navigating.</p><pre>// example4/index.js<br>...<br><strong>await page.setExtraHTTPHeaders({<br>	&#39;x-test-header&#39;: &#39;much wow!&#39;<br>})<br>...</strong></pre><pre>// navigate to a page<br>const pageUrl = &#39;<a href="https://spacex-ships.now.sh&/#39;">https://spacex-ships.now.sh&#39;</a><br>const response = await page.goto(pageUrl, {waitUntil: &#39;networkidle2&#39;})<br>console.log(separator)<br><strong>console.log(response.request().headers())</strong><br>console.log(separator)<br>...</pre><p>Now when we run our script, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBwR3j5r8-U9oNyQ-geVLA.png" /></figure><p>Additionally, we can avoid hitting the API altogether and just return our own response instead with mock data.</p><p>For this, we need the following:</p><ol><li>We need to setRequestInterception(true)</li><li>Then we need to listen for &#39;request&#39; events like we did for responses earlier.</li><li>Once we’ve intercepted a target request, we need to tell Puppeteer to return our own response rather than sending the request to the API.</li></ol><p><strong>For #1</strong>, we just add one line, and this can be done once we have a <em>Page </em>object.</p><pre>...<br>const page = await browser.newPage()</pre><pre><strong>// Enable request interception<br>await page.setRequestInterception(true)</strong></pre><p><strong>For #2</strong>, we’ll usepage.on(&#39;request&#39;) to intercept /graphql POST requests, and tell Puppeteer to send any other request on its way.</p><p>First let’s define our mock data. In the screenshot of the browser’s network tag from a previous example we can see that the shape of the response JSON looks like this:</p><pre>{<br>  data: {<br>    ships: [<br>    {<br>      active: true,<br>      class: 15252765,<br>      name: &#39;GO Ms Tree&#39;,<br>      image: &#39;<a href="https://i.imgur.com/MtEgYbY.jpg&#39;">https://i.imgur.com/MtEgYbY.jpg&#39;</a>,<br>      id: &#39;GOMSTREE&#39;,<br>      year_built: 2015,<br>      type: &#39;High Speed Craft&#39;<br>    },<br>    ...<br>    ]<br>  }<br>}</pre><p>Thus, if we want our response to succeed it needs to be in the same shape and with the same types.</p><pre>const mockData = JSON.stringify({<br>            data: {<br>                ships: [{<br>                    active: true,<br>                    class: 12345678,<br>                    name: &#39;Puppeteer is not a SpaceX Ship!!&#39;,<br>                    image: &#39;<a href="https://bit.ly/2xP93Pd">https://bit.ly/2xP93Pd</a>&#39;,<br>                    id: &#39;PUPPETEER&#39;,<br>                    year_built: 2017,<br>                    type: &#39;Browser Automation Tool&#39;<br>                }]<br>            }<br>        })</pre><p>For our purposes, we just return one mock “ship” and notice that we JSON.stringify() the JavaScript object.</p><p><strong>For #3</strong>, we can now tell Puppeteer to respond with our mockData when the page tries to request the ships data from the SpaceX API.</p><pre>await page.on(&#39;request&#39;, async request =&gt; {</pre><pre>    <strong>const isGraphQL = request.url().includes(&#39;/graphql&#39;)<br>    const isPOST = request.method() === &#39;POST&#39;</strong></pre><pre><strong>    if (isGraphQL &amp;&amp; isPOST)</strong> {<br>        console.log(&#39;\n 🚀 We got one!: &#39;, request.url())<br>        <strong>await request.respond</strong>({<br>            status: 200,<br>            contentType: &#39;application/json&#39;,<br>            body: <strong>mockData</strong>               <br>        })<br>    } else {<br>        <strong>request.continue()</strong><br>    }<br>})</pre><p>The else is important here because we setRequestInterception(true) This means Puppeteer will block the requests unless you tell Puppeteer what to do with them.</p><p>Thus, we not only tell Puppeteer to send our mock data back for /graphql requests, but if Puppeteer intercepts a request that we’re not interested in, then we tell Puppeteer to send it on its way with request.continue() .</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o84sF21zQYacFcl68%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fstarwars-movie-star-wars-3o84sF21zQYacFcl68&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o84sF21zQYacFcl68%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="186" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d9d1bd0845a16971749951dd0029398/href">https://medium.com/media/4d9d1bd0845a16971749951dd0029398/href</a></iframe><p>Let’s also have Puppeteer take a screenshot after the page loads so we can verify our mockData got rendered.</p><p>await page.screenshot({path: ‘./puppeteer-example5.png’})</p><p>The full code example looks like this:</p><pre>const puppeteer = require(&#39;puppeteer&#39;);</pre><pre>(async () =&gt; {</pre><pre>    // Puppeteer stuff<br>    const browser = await puppeteer.launch({headless: false})<br>    try {<br>        const page = await browser.newPage()</pre><pre>        // Step1: Enable request interception<br>        await page.setRequestInterception(true)<br>        </pre><pre>        // Step 2: define mock data<br>        const mockData = JSON.stringify({<br>            data: {<br>                ships: [{<br>                    active: true,<br>                    class: 12345678,<br>                    name: &#39;Puppeteer is not a SpaceX Ship!!&#39;,<br>                    image: &#39;<a href="https://bit.ly/2xP93Pd&#39;">https://bit.ly/2xP93Pd&#39;</a>,<br>                    id: &#39;PUPPETEER&#39;,<br>                    year_built: 2017,<br>                    type: &#39;Browser Automation Tool&#39;<br>                }]<br>            }<br>        })</pre><pre>        // Step 3: Intercept GQL requests and return mockData<br>        await page.on(&#39;request&#39;, async request =&gt; {</pre><pre>            const isGraphQL = request.url().includes(&#39;/graphql&#39;)<br>            const isPOST = request.method() === &#39;POST&#39;<br>            if (isGraphQL &amp;&amp; isPOST) {<br>                console.log(&#39;\n 🚀 We got one!: &#39;, request.url())<br>                await request.respond({<br>                    status: 200,<br>                    contentType: &#39;application/json&#39;,<br>                    body: mockData               <br>                })<br>            } else {<br>                request.continue()<br>            }<br>        })</pre><pre>        // navigate to a page<br>        const pageUrl = &#39;<a href="https://spacex-ships.now.sh&/#39;">https://spacex-ships.now.sh&#39;</a><br>        await page.goto(pageUrl, {waitUntil: &#39;networkidle0&#39;})<br>        await page.waitForSelector(&#39;img&#39;)<br>        await page.screenshot({path: &#39;./puppeteer-example5.png&#39;})</pre><pre>} finally {<br>        console.log(&#39;Closing the browser...\n&#39;)<br>        await browser.close()<br>    }<br>})();</pre><p>And let’s check our screenshot to see what we got!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ucscO6yOVM-BtGSvtAlZ9w.png" /><figcaption>Screenshot taken by Puppeteer</figcaption></figure><p>🎉</p><blockquote><strong>Note</strong>: I’ve noticed some weirdness between headless and headful modes. It seems like my page doesn’t want to render the mocked response in headless mode.</blockquote><blockquote>I’ve also seen some <a href="https://github.com/puppeteer/puppeteer/issues/665">issues</a> on the Puppeteer GitHub regarding differences between headless and headful modes. So just keep an eye out. In this case, the screenshots were always capturing the loading spinner no matter how long I told Puppeteer to wait.</blockquote><p>Anyway… onward! What else can we look at?</p><h3>Certificate Details</h3><p>Browsers nowadays warn you when you’re navigating to a site that does not have a valid certificate. This can happen if the page is served over HTTP and not HTTPS (i.e., does not have a cert and thus is not encrypting the web traffic), <em>or </em>if the site has a cert but it’s not signed by a known Certificate Authority (CA).</p><p>Most sites that you browse should have a valid certificate that you can view by clicking the lock 🔒 icon in your browser’s address bar, usually to the left of the URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*A2UiZ8GAacjabQgzvbXHRQ.png" /><figcaption>Certificate for https://spacex-ships.now.sh</figcaption></figure><p>I’ve deployed the site via <a href="https://vercel.com/">Vercel</a> (formerly Zeit), and looks like they’ve used <a href="https://letsencrypt.org/">Let’s Encrypt</a> as the certificate authority for *.now.sh domain names.</p><p>Puppeteer can let us inspect some of this information, so let’s update our script.</p><p>We can get rid of a lot of what was there for inspecting network requests, and instead grab the response from the navigation to the page. From there, we can grab the securityDetails</p><pre>// example6/index.js<br>...<br>const page = await browser.newPage()</pre><pre>// navigate to a page<br>const pageUrl = &#39;<a href="https://spacex-ships.now.sh&/#39;">https://spacex-ships.now.sh&#39;</a><br><strong>const response</strong> = await page.goto(pageUrl, {waitUntil: &#39;networkidle0&#39;})<br><strong>const cert = await response.securityDetails()<br>console.log(cert)</strong><br>...</pre><p>This will yield:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDlVgT9CrjuuaK1mmI_GHQ.png" /><figcaption>Certificate information for https://spacex-ships.now.sh</figcaption></figure><p>We can also log those timestamps as actual Date objects if we want.</p><pre>const cert = await response.securityDetails()<br><strong>console.log({<br>    ...cert,<br>    _validFrom: new Date(cert._validFrom * 1000),<br>    _validTo: new Date(cert._validTo * 1000)<br>})</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCt4eg2dEo_lJzX2EEgruQ.png" /></figure><h3>Conclusion</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxUA7ba9aksCuKR9dgA%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcorsairgaming-star-wars-lightning-xUA7ba9aksCuKR9dgA&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxUA7ba9aksCuKR9dgA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/b160eb1cc880944ee1f5ca8beeedeb2e/href">https://medium.com/media/b160eb1cc880944ee1f5ca8beeedeb2e/href</a></iframe><p>At this point you should be able to navigate your way around Puppeteer. Listening for console messages is very similar to listening for network requests. You listen for &#39;console&#39; events rather than &#39;request&#39; or &#39;response&#39; events, and get to filtering. There are a number of other events which can be listened for, so be sure to check out the Puppeteer documentation.</p><p>I’m also keeping my eye on <a href="https://github.com/microsoft/playwright">Playwright</a>. I <a href="https://blog.logrocket.com/playwright-vs-puppeteer/">read</a> <a href="https://www.infoq.com/news/2020/01/playwright-browser-automation/">somewhere</a> that the folks that made Puppeteer left Google, joined Microsoft, and made Playwright with almost the same API as Puppeteer, and looks like it can work with Safari in addition to Chrome and Firefox. <em>And </em>it looks like version 1.0 has been released!</p><p>Anyway, hope this helps! Let me know if you have questions 🙂</p><h3>Links</h3><ul><li>Puppeteer playground: <a href="https://try-puppeteer.appspot.com/">https://try-puppeteer.appspot.com/</a></li><li>Puppeteer documentation: <a href="https://pptr.dev/">https://pptr.dev/</a></li><li>SpaceX Graphiql: <a href="https://api.spacex.land/graphql/">https://api.spacex.land/graphql/</a></li><li>spacex-ships repo: <a href="https://gitlab.com/joel.mariano.ramos/spacex-ships">https://gitlab.com/joel.mariano.ramos/spacex-ships</a></li><li>Puppeteer headless vs headful differences GitHub issue: <a href="https://github.com/puppeteer/puppeteer/issues/665">https://github.com/puppeteer/puppeteer/issues/665</a></li><li>Vercel: <a href="https://vercel.com/">https://vercel.com/</a></li><li><a href="https://www.infoq.com/news/2020/01/playwright-browser-automation/">https://www.infoq.com/news/2020/01/playwright-browser-automation/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8010e374ff7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ramojol/how-ive-been-using-puppeteer-b8010e374ff7">How I’ve been Using Puppeteer</a> was originally published in <a href="https://medium.com/ramojol">ramosly | blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Context Managers and the “with” Statement]]></title>
            <link>https://medium.com/ramojol/python-context-managers-and-the-with-statement-8f53d4d9f87?source=rss----d27fe4c47e7c---4</link>
            <guid isPermaLink="false">https://medium.com/p/8f53d4d9f87</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[context-managers]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Joel Ramos]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 01:12:54 GMT</pubDate>
            <atom:updated>2018-02-20T21:52:00.264Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re like me and you are relatively new to Python, you may have come across the term “context manager” while reading documentation, or researching a library that you are thinking about using. For a while, I glossed over this term to get what I needed done, but in the back of my mind I was still curious. Along the same lines, Python has this <em>with </em>keyword. What’s up with that thing?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*vgmRQe5iMh3Si0gUVjQa0g.gif" /></figure><p>In this post, I will go over what I have learned about context managers, the <em>with</em> keyword, and how they are related.</p><p>As it turns out, context managers and the <em>with </em>keyword go hand-in-hand!</p><p>I had read here and there that when you want to read data from a file, it is better to use the <em>with </em>keyword to do so because it automatically closes the file after you leave the scope of the “with statement.” This as opposed to having to remember to close the file when you’re done with it.</p><pre><strong>with</strong> open(&#39;filename.txt&#39;) <strong>as</strong> f:<br>    text = f.read()<br>    <strong>print</strong>(text)</pre><pre><em># File is closed by this point</em></pre><h4>Yeah yeah, but still, what <em>is </em>a context manager?</h4><p>Context managers are just Python classes that specify the <em>__enter__</em> and <em>__exit__</em> methods. Actually, as <a href="https://www.python.org/dev/peps/pep-0343/">PEP 343</a> states:</p><blockquote>This PEP adds a new statement &quot;with&quot; to the Python language to make<br>it possible to factor out standard uses of try/finally statements.<br><br>In this PEP, context managers provide __enter__() and __exit__()<br>methods that are invoked on entry to and exit from the body of the<br>with statement.</blockquote><p>As lack-luster as that sounds, just specifying these two methods in a class makes that class a “context manager.” As stated, the <em>__enter__ </em>method is where you put the code that is going to run before you enter the scope of the <em>with </em>block. Similarly, the <em>__exit__ </em>method is where you put the code that you want to execute when you leave the scope of the <em>with </em>block.</p><p>In the example above, <em>open() </em>is opening the specified file, then we do what we need with the contents of the file, then we leave the <em>with</em> block and the file is closed without us having to do any extra work.</p><p>This is nice and all, but if you think about it, this concept can be applied to other scenarios where you want to have a reusable way to create a “state of the world” for code to run in, rather than typing the same thing over and over. An example of where context managers <em>could</em> be useful is in creating database connections, and then closing them when finished.</p><pre><strong>from</strong> sqlalchemy <strong>import</strong> create_engine<br><strong>from</strong> sqlalchemy.orm <strong>import</strong> sessionmaker<br></pre><pre><strong>class</strong> SQLAlchemyDBConnection(<strong>object</strong>):<br><em>    &quot;&quot;&quot;SQLAlchemy database connection&quot;&quot;&quot;</em></pre><pre>    <strong>def</strong> __init__(self, connection_string):<br>        self.connection_string = connection_string<br>        self.session = None</pre><pre>    <strong>def</strong> __enter__(self):<br>        engine = create_engine(self.connection_string)<br>        Session = sessionmaker()<br>        self.session = Session(bind=engine)<br>        <strong>return</strong> self</pre><pre><strong>    def</strong> __exit__(self, exc_type, exc_val, exc_tb):<br>        self.session.close()</pre><p>Because we specified the <em>__enter__ </em>and <em>__exit__ </em>methods, we can use this class with the <em>with </em>keyword.</p><pre>conn_str = &#39;mssql+pydobc://server_name/db_name?driver=SQL+Server&#39;</pre><pre><strong>with</strong> SQLAlchemyDBConnection(conn_str) as db:<br>    customer = db.session.query(Customer).filter_by(id=123).one()<br>    print(customer.name)</pre><p>Alternatively, you can also write the <em>with </em>statement this way:</p><pre>conn_str = &#39;mssql+pydobc://server_name/db_name?driver=SQL+Server&#39;</pre><pre>db = SQLAlchemyDBConnection(conn_str)<br><strong>with</strong> db:<br>    customer = db.session.query(Customer).filter_by(id=123).one()<br>    <strong>print</strong>(customer.name)</pre><p>In these examples I’ve used a <a href="http://www.sqlalchemy.org/">SQLAlchemy</a> database connection, but you could create one for <a href="https://api.mongodb.org/python/current/">MongoDB</a>, or some other database querying tool.</p><pre><strong>from</strong> pymongo <strong>import</strong> MongoClient</pre><pre><br><strong>class</strong> MongoDBConnection(<strong>object</strong>):<br><em>    &quot;&quot;&quot;MongoDB Connection&quot;&quot;&quot;</em></pre><pre>    <strong>def</strong> __init__(self, host=&#39;localhost&#39;, port=&#39;27017&#39;)<br>        self.host = host<br>        self.port = port<br>        self.connection = <strong>None</strong></pre><pre>    <strong>def</strong> __enter__(self):<br>        self.connection = MongoClient(self.host, self.port)<br>        <strong>return</strong> self</pre><pre><strong>    def</strong> __exit__(self, exc_type, exc_val, exc_tb):<br>        self.connection.close()</pre><p>We’d use this in a similar way.</p><pre>mongo = MongoDBConnection()<br><strong>with</strong> mongo:<br>    collection = mongo.connection.MyDbName.Customers<br>    customer = collection.find({&#39;_id&#39;: 123})<br>    print(customer.get(&#39;name&#39;))</pre><h4>But wait! There’s more!</h4><p>Not only is this awesome for reusability, but it turns out that you can have your code be within the context of multiple context managers at the same time!</p><pre>sql_conn_str = &#39;mssql+pydobc://server_name/db_name?driver=SQL+Server&#39;</pre><pre>mongo = MongoDbConnection(&#39;10.9.8.7&#39;, 3000)<br>sql = SQLAlchemyDBConnection(sql_conn_str)</pre><pre><strong>with</strong> mongo, sql:<br><em>    # get data from SQL</em><br>    customer = sql.session.query(Customer).first()</pre><pre>   <em> # insert data into mongo</em><br>    collection = mongo.connection.DbName.CollectionName<br>    collection.insert({<br>        customer_id: customer.cust_id,<br>        name: customer.name})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*7su4g6ks-2vEOt18mSce6w.gif" /></figure><p>You can “nest” as many context managers as you like using the <em>with </em>statement. In fact, rather than comma-separating them, you <em>could actually</em> nest them.</p><pre><strong>with</strong> MongoDbConnection() <strong>as</strong> mongo:<br>    <strong>with</strong> SQLAlchemyDBConnection(conn_str) <strong>as</strong> sql:<br>        <em># Do stuff</em></pre><p>You can also comma-separate this longer version. I prefer to save them to variables first and comma-separate those variables. It’s really up to you.</p><p>Speaking of it’s-up-to-you, you don’t have to do this with database connections, nor am I suggesting that you should. I just thought it a good example of setting up a particular state for code to run in, and then doing away with it.</p><p>Also, as I mentioned towards the beginning, you might have come across the term “context manager” in documentation, but weren’t sure what it meant at the time. But hopefully, now you’ll have a better understanding of what’s going on.</p><p>Here is an example from the <a href="http://docs.python-requests.org/en/latest/api/?highlight=context%20manager"><em>requests</em></a> library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMUTAcY2t1FRG8TgFa0h4A.png" /></figure><p>For those that want to get deeper into the weeds, check out the docs on the <a href="https://docs.python.org/2/reference/compound_stmts.html#with">with</a> statement. There is also the <a href="https://docs.python.org/2/library/contextlib.html">contextlib</a> library in the Python standard library that specifies a contextmanager decorator. This let’s you turn a function into a context manager, but I’ll let you read up on that.</p><p>While I have seen posts by others about context managers, I hadn’t come across a post about nesting them in with statements, outside of the documentation. I’ve not explored this very deeply, but it seems that interesting scenarios are possible where your code could be within the context of a database connection <em>and </em>a requests Session. That might turn out to be a ridiculous scenario, but hey, you could do it!</p><p>Anyway, hopefully someone finds this info useful. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f53d4d9f87" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ramojol/python-context-managers-and-the-with-statement-8f53d4d9f87">Python Context Managers and the “with” Statement</a> was originally published in <a href="https://medium.com/ramojol">ramosly | blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Puppeteer: Getting into Coding with Browser Automation]]></title>
            <link>https://medium.com/ramojol/puppeteer-getting-into-coding-with-browser-automation-6d4ad1364a75?source=rss----d27fe4c47e7c---4</link>
            <guid isPermaLink="false">https://medium.com/p/6d4ad1364a75</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Joel Ramos]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 00:48:08 GMT</pubDate>
            <atom:updated>2020-05-03T17:09:36.013Z</atom:updated>
            <content:encoded><![CDATA[<h3>Puppeteer Browser Automation for Beginners</h3><figure><img alt="Puppeteer logo" src="https://cdn-images-1.medium.com/max/290/1*kk8ovQKB-45FsZ8TZM-vjg.png" /></figure><p>So there I was, typing away, writing a post about how I’ve been using Puppeteer at work and the post was getting fairly long. I kept coming across things where I thought to myself, “Someone just starting out might get tripped up here 🤔”</p><p>I showed the draft to coworkers and they were like, “Yeah this could be broken up into separate posts.”</p><p>Thus, I thought I’d make a separate post! 🚀 This one is about getting set up with browser automation, specifically with Puppeteer.</p><blockquote>Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the <a href="https://chromedevtools.github.io/devtools-protocol/">DevTools Protocol</a>. Puppeteer runs <a href="https://developers.google.com/web/updates/2017/04/headless-chrome">headless</a> by default, but can be configured to run full (non-headless) Chrome or Chromium.<br>- <a href="https://pptr.dev/">https://pptr.dev/</a></blockquote><p>In my opinion, browser automation is a good way to get started with coding. You don’t have to write many lines <em>and </em>once you get a taste of having your code drive a web browser, you’ll be hooked.</p><p>Classics like, “Whoa.” and “This could be doing my timesheet for me… 🤔” will flood the ol’ brain-waves as you start to realize all the tedious, manual shit you’ve been doing, that you hate doing, that code could be doing for you 💅</p><h3>An Analogy</h3><p>Like driving a car, we don’t necessarily need to know how one works in order to drive one. The same goes with browser automation. As long as we know how to drive, or in this case use Puppeteer, we can go places 🚗</p><p>We also use cars because they get us to the store in minutes and can carry way more stuff than we can. I’m just saying, sometimes you need to buy a TV, or it’s raining outside 🤷‍♂ Similarly, Puppeteer will do everything faster than you can, and it won’t forget to do something you’ve told it to do.</p><p>What follows should cover everything you need to get up and running, but let me know if I’ve missed something 🤔</p><h3>Prerequisites for getting started 🛫</h3><p>First, here is a list of things you’ll need:</p><ol><li>✍️ A text editor or IDE for writing JavaScript, like VS Code. There are others but… <a href="https://code.visualstudio.com/download">just use VS Code</a>.</li><li>💻 NodeJS installed. Go to <a href="https://nodejs.org/en/">nodejs.org</a>, then download and install NodeJS if you haven’t already.</li><li>📦 I’ll be using theyarn package manager to install Puppeteer, but you can use npm if you don’t already have yarn or don’t want to deal with installing it. You can install it from <a href="https://classic.yarnpkg.com/en/docs/getting-started">https://classic.yarnpkg.com/en/docs/getting-started</a></li><li>🤓 A terminal.<br>On an Apple computer, you can press Cmd+Spacebar, search for “terminal,” and click the result or press Enter to launch it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YW1-m4YldHncn-e6vxPpXg.jpeg" /><figcaption>The Space Bar 🍺</figcaption></figure><blockquote><strong>Note: </strong>On Windows, you can press Windows-Key and search for “cmd” or “powershell” and use either one. <br>Since I’m using a mac book, the commands I use for creating folders and navigating the file system will be for the terminal.</blockquote><h3>Let’s create a smol project</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F7NoNw4pMNTvgc%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F7NoNw4pMNTvgc%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcWk3YThuNTBkdDFuZWYyMWkyeHViYjZqbjlxdXo2djh2cmNmZG5mciZlcD12MV9naWZzX2dpZklkJmN0PWc%2F7NoNw4pMNTvgc%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdbba5d6e867b852f940c62f9bcb85d4/href">https://medium.com/media/cdbba5d6e867b852f940c62f9bcb85d4/href</a></iframe><p>Create a folder called <em>puppeteer-example</em> for our script.</p><p>$ mkdir puppeteer-example &amp;&amp; cd puppeteer-example</p><p>mkdir for “make directory” and cd for “change directory”</p><p>Now let’s use yarn to initialize the project and create a package.json file.</p><blockquote>If you don’t want to use <em>yarn</em> or deal with installing it, you can use npm init in place of yarn init below, and use <em>npm install</em> in place of <em>yarn add</em> below. Everything else should be the same.</blockquote><p>$ yarn init</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*USX98jf0fRC9C1UYXExEhw.gif" /></figure><p>Run yarn add puppeteer to install it.</p><p>$ yarn add puppeteer</p><p><strong>Note</strong>: at the time of this writing, Puppeteer 3.0 has just come out and is only compatible with newer versions of NodeJS. So you might get an error like this if you already had Node installed but have not updated in a while:</p><figure><img alt="Gif of the installation error you’ll get when installing Puppeteer 3.0 with Node versions older than 10.18.1" src="https://cdn-images-1.medium.com/max/1024/1*1J-L9W-OZcZbaPhEhNPf8w.gif" /><figcaption>Puppeteer 3.0 installation error with Node versions older than 10.18.1</figcaption></figure><p>If this is the case, you could install an older version of puppeteer, but you should probably update Node. You can follow this guide for <a href="https://phoenixnap.com/kb/update-node-js-version">how to update Node to the latest version for Linux, Mac, and Windows</a>.</p><p>Now let’s create a file where we’ll put our code.</p><p>$ touch index.js</p><p>Pay no attention to the creepy command name; I just work here.</p><p>The following will open the current directory in VS Code, but you can use whichever editor you want.</p><p>$ code .</p><h3>Writing 👏 A 👏 Script 👏</h3><p>First thing’s first. Like that scene in the Matrix where Neo learns kung fu, we need to teach Node how to speak Puppeteer. So let’s open our newly-created <em>index.js</em> file, and pull in Puppeteer.</p><pre>// index.js<br>const puppeteer = require(&#39;puppeteer&#39;);</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7btNhMBytxAM6YBa%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fkeanu-reeves-matrix-the-3o7btNhMBytxAM6YBa&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o7btNhMBytxAM6YBa%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="217" frameborder="0" scrolling="no"><a href="https://medium.com/media/49ce07ec0c9e62797925a7950653f7f7/href">https://medium.com/media/49ce07ec0c9e62797925a7950653f7f7/href</a></iframe><p>Now let’s add an async <a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">IIFE (Immediately Invoked Function Expression)</a> that will execute when we run the file. We&#39;ll put all our Puppeteer stuff in there.</p><pre>// index.js<br>const puppeteer = require(&#39;puppeteer&#39;);</pre><pre><strong>(async () =&gt; {<br>    // Puppeteer stuff <br>})();</strong></pre><blockquote>P.S. if you forget to put the semi-colon at the end of the <em>require(&#39;puppeteer&#39;);</em> line, you might be in for hours of Googling trying to figure out why you&#39;re getting a<em>TypeError: require(...) is not a function</em> error. I imagine this is because the next thing we do is add an opening parenthesis, so Node thinks we&#39;re trying to run something like<em>require(&#39;puppeteer&#39;)(...)</em> Anyway... add the semi-colon!</blockquote><p>Every command/function in Puppeteer is “asynchronous.” This means when you execute one of them, the function will finish immediately and continue on with the rest of the program <em>before </em>it has gotten the result. So we need to await the Puppeteer functions, and we can only use the await keyword inside of an async function in JavaScript. Rules are rules.</p><p>First, we need an instance of a <em>Browser</em> and then we can use it to create a new <em>Page</em>. The puppeteer.launch() function will open an actual browser when we run it, and hand us a back a code object representing that browser.</p><p>When we want to hold onto the return-value of a function, we need to assign it to a variable.</p><p>await puppeteer.launch()</p><p>vs</p><p>const browser = await.puppeteer.launch()</p><p>The first example discards the return value, but we need it because it has functions we want to use, like newPage()! So let’s add the two lines in bold below.</p><pre>// index.js<br>const puppeteer = require(&#39;puppeteer&#39;);</pre><pre>(async () =&gt; {</pre><pre>    // Puppeteer stuff <br>    <strong>const browser = await puppeteer.launch({ headless: false });<br>    const page = await browser.newPage();</strong><br>})();</pre><p>Sweet. At this point, we have a <em>Page</em> “object.”</p><p>Most of the actions we do in Puppeteer are done on the Page object, not the browser. Technically we can have multiple pages and switch between them, so we need create a new page and work with that.</p><p>There is a little more to do before we can run our script. So, onward!</p><blockquote><strong>Note:</strong> we’re passing the <em>headless</em> option and setting it to <em>false</em> to change the default. Setting <em>headless</em> to <em>false</em> makes the graphical user interface (GUI) actually display so you can see what Puppeteer is doing. By default, Puppeteer will drive the browser without displaying the GUI, because it’s faster and usually unnecessary unless you’re debugging something.</blockquote><p>Now we just need to tell Puppeteer to take us somewhere. So let’s do that real quick.</p><pre>// index.js <br>const puppeteer = require(‘puppeteer’);</pre><pre>(async () =&gt; {</pre><pre>    // Puppeteer stuff <br>    const browser = await puppeteer.launch({ headless: false });<br>    const page = await browser.newPage();</pre><pre><strong>    // navigate to a page<br>    await page.goto(&#39;https://www.google.com&#39;)</strong><br>})();</pre><p>Let’s also add a bit of house-keeping to close the browser after our script runs. We’ll wrap what we have so far in a try-finally block so that no matter what happens, we always close the browser.</p><pre>// index.js<br>const puppeteer = require(&#39;puppeteer&#39;);</pre><pre>(async () =&gt; {</pre><pre>    // Puppeteer stuff <br>    const browser = await puppeteer.launch({ headless: false });        <br>    <strong>try {</strong><br>	const page = await browser.newPage();<br>	<br>	// navigate to a page<br>	await page.goto(&#39;https://www.google.com&#39;)<br>    <strong>} finally {<br>        console.log(&#39;Closing the browser...&#39;)<br>        await browser.close();<br>    }</strong><br>})();</pre><p>Notice that are first line where we run puppeteer.launch() was moved outside the try-finally .</p><p>This is because curly braces {} define a scoped “block” of code, and since we want to close the browser within the scope of the finally block, we are moving that line up and outside of the scope of the try block so that it is accessible within the scope of the finally block.</p><p>If we hadn’t done this, we would get a ReferenceError like this, and the browser wouldn’t close:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qSQrjnz9LLRshCujkcUng.png" /></figure><p>And then the terminal would sit there until you press Ctrl+C to terminate the running process.</p><p>Alright well now that I’ve spilled the beans on how to run this thing, let’s run what we have so far and make sure we’re on the right track.</p><p>$ node index.js</p><figure><img alt="Running the initial index.js file with “node index.js” in the terminal." src="https://cdn-images-1.medium.com/max/1024/1*wQD5ku0xZh6PP8sAXPA8SQ.gif" /><figcaption>Running the file with “node index.js”</figcaption></figure><p>Neat 🎉</p><p>Now what? 🤔</p><p>Welp, let’s search for something!</p><p>Up until now, we have not actually done any interacting with the page. This part requires us to do a little digging. Keeping the car analogy going, we’ll need to look under the hood of the browser a bit in order to continue.</p><p>Bear with me here, as we’re going to get a little technical 😅</p><h3>Looking Under the Hood 🚗</h3><p>Puppeteer, and every other browser-automation tool, uses what are called <strong>locators</strong> or <strong>selectors</strong> to “locate”<em> </em>elements on the page. There are two steps to creating a locator.</p><h3>Step 1: Find the Element</h3><p>First, we can right-click the field on the page and choose the “Inspect” option in the context menu to expose the html element in the html-element hierarchy known as the Document Object Model (DOM). The DOM is basically the structure, or the scaffolding of the page.</p><figure><img alt="Gif of right-clicking the search field on Google.com and clicking “Inspect” to show the input element in the DOM inspector." src="https://cdn-images-1.medium.com/max/1024/1*oA87jSaab0hIK890JWvTSw.gif" /></figure><p>This not-so-secret window is known as Developer Tools. It’s used a lot by software developers and people like me who work on software development teams to test and make sure things are working as expected.</p><p>From within the Elements tab of the dev tools window, we can press Cmd+F (Ctrl+F on Windows) to expose the search field where we can test out our selectors.</p><p>The element we’re interested in is the &lt;input... &gt; tag that is highlighted when the window opens. The browser highlights it since this is the element we right-clicked before clicking <em>Inspect.</em></p><figure><img alt="Screenshot of the DOM after right-clicking the search field on the Google homepage, and clicking “Inspect”" src="https://cdn-images-1.medium.com/max/1024/1*Z574w7C1Zp8qPBMGC5xdJw.png" /></figure><h3>Step 2: Write the Selector</h3><p>Selectors are bits of text that browsers understand which find, or “select,” an html element / set of html elements in the current page.</p><p>There are two main types of selectors:</p><ul><li>CSS selectors (Cascading Style Sheets)</li><li>XPaths (XML Path Language)</li></ul><p>I usually use CSS selectors so let’s go with that.</p><p>Now, looking at the &lt;input&gt; element in the DOM, we need to use what we see to construct our selector so that it only selects this element. With CSS selectors, we can use the name of the html tag to select all elements in the DOM with that tag, which in this case is input.</p><figure><img alt="Screenshot of the DOM inspector after searching for “input” and getting 14 results." src="https://cdn-images-1.medium.com/max/1024/1*TMtB1_eMJOCjmDWSRLxSbA.png" /><figcaption>14 results when searching the DOM for “input”</figcaption></figure><p>For better or for worse, the search not only runs selectors but also does text search. So, you’re gonna get every instance of “input” in the DOM, which is no help.</p><p>Not only that, but now we’ve lost where our element was 😤 We can get it back by right-clicking it and choosing “Inspect” again in the page.</p><p>Okay, so… that didn’t work. We need a selector that’s more specific. We’ll have to use the “attributes” of the input element to narrow down the results from 14, to just the one.</p><p>Hey, look at that, it has an attribute called name with a value of q, perhaps for “query” 🤔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbvfD6i4QAUohRL8r05SUg.png" /></figure><p>The way we select an element based on one of its attributes is by enclosing the attribute and value in square brackets: input[name=&quot;q&quot;] If we try typing <em>this </em>into the element search, we see that the browser highlights our target input element in green. We have a match!</p><figure><img alt="Screenshot of the DOM inspector with input[name=”q”] in the search and the targeted input element highlighted green." src="https://cdn-images-1.medium.com/max/1024/1*Phn4iC6hYU_40HbrVuRT9A.png" /></figure><h3>Tell Puppeteer the Good News</h3><p>Now that we know our selector works, we can tell Puppeteer how to find the search field and enter searches for us.</p><p>I’m gonna copy the original index.js file into an example2/ folder to keep it as a separate version.</p><p>So, now our example2/index.js file looks like this:</p><pre>const puppeteer = require(&#39;puppeteer&#39;);</pre><pre>(async () =&gt; {</pre><pre>    // Puppeteer stuff<br>    const browser = await puppeteer.launch({ headless: false })<br>    try {<br>        const page = await browser.newPage()</pre><pre>        // navigate to a page<br>        await page.goto(&#39;<a href="https://www.google.com&/#39;">https://www.google.com&#39;</a>)<br>        <strong>await page.type(&#39;input[name=&quot;q&quot;]&#39;, &#39;tesla stock&#39;)<br>        await page.keyboard.press(&#39;Enter&#39;)<br>        await page.waitForNavigation()</strong><br>    } finally {<br>        console.log(&#39;Closing the browser...&#39;)<br>        await browser.close()<br>    }<br>})();</pre><p>We tell Puppeteer to type &#39;tesla stock&#39; into the input[name=&quot;q&quot;] field with the page.type() function.</p><p>Then we tell Puppeteer to press Enter.</p><p>Then, since a new page is going to load, we tell puppeteer to page.waitForNavigation()</p><p>Let’s run it! 🏃</p><p>$ node example2/index.js</p><figure><img alt="Gif of Puppeteer launching the browser, navigating to Google.com, searching for “tesla stock” and pressing Enter." src="https://cdn-images-1.medium.com/max/1024/1*rsAacCd69b6H4OFrKS4y0Q.gif" /><figcaption>Puppeteer google-ing “tesla stock”</figcaption></figure><p>This happens to work, but it is generally a good idea to make your automation more robust by adding “waits” before interacting with elements. If your script doesn’t need it, then great! But if it’s not succeeding consistently, then it might be a sign that you need to wait for the element to be visible before trying to interact with it.</p><pre>const puppeteer = require(&#39;puppeteer&#39;);</pre><pre>(async () =&gt; {</pre><pre>    // Puppeteer stuff<br>    const browser = await puppeteer.launch({ headless: false })<br>    try {<br>        const page = await browser.newPage()</pre><pre>        // navigate to a page<br>        await page.goto(&#39;<a href="https://www.google.com&/#39;">https://www.google.com&#39;</a>)</pre><pre><strong>        const inputSelector = &#39;input[name=&quot;q&quot;]&#39;<br>        await page.waitForSelector(inputSelector, { visible: true })</strong><br>        await page.type(<strong>inputSelector</strong>, &#39;tesla stock&#39;)<br>        await page.keyboard.press(&#39;Enter&#39;)<br>        await page.waitForNavigation()<br>    } finally {<br>        console.log(&#39;Closing the browser...&#39;)<br>        await browser.close()<br>    }<br>})();</pre><p>The other change I made above was to save the selector in the inputSelector variable so that it can be reused in both the page.waitForSelector() function, and the page.type() function. Don’t repeat yourself! The last thing you want is for the selector to stop working and then have to update it in a million places. If you save it to a variable first, then if it changes you just update the variable and everything else gets the change for free.</p><p>The page.goto() function also takes an optional “options” object as its second argument where you can tell Puppeteer to wait for all the browser requests to complete before continuing. (More on this in the <a href="https://pptr.dev/#?product=Puppeteer&amp;version=v3.0.0&amp;show=api-pagegotourl-options">page.goto() docs</a>.)</p><p>await page.goto(url, { waitUntil: &#39;networkidle0&#39; })</p><p><em>Another</em> thing you can do if you’re planning to use Puppeteer to automate tasks, is remove the { headless: false } options object from the call topuppeteer.launch(). This way Puppeteer will go back to using the default mode, which is headless. Your script will run without having to actually display the browser, and will also run more quickly.</p><p>We could go on from here with page.click(), but… I think you get the idea.</p><p>You can look at the <a href="https://pptr.dev/#?product=Puppeteer&amp;version=v3.0.0&amp;show=api-class-page">puppeteer documentation</a> see all the functions Puppeteer Page objects have available.</p><p>The best tools, in my humble opinion, tend to let you describe <em>what </em>you want to do, rather than make you describe <em>how </em>to do it. Puppeteer seems to do a good job of this. My experience using it has been largely positive, but I’m curious what others think and if/how others are using it.</p><p>Anyway, hopefully this is helpful. I’m thinking about making a YouTube video for this 🤔 Hit me up here, or on Twitter <a href="https://twitter.com/ramojol">@ramojol</a> if I left something out, made a mistake, or if you have questions 😅 🍻</p><h3>Links</h3><ul><li><a href="https://www.w3schools.com/xml/dom_intro.asp">W3Schools DOM Introduction</a></li><li><a href="https://www.w3schools.com/cssref/css_selectors.asp">W3Schools CSS Selector Reference</a></li><li><a href="https://www.w3schools.com/xml/xpath_intro.asp">W3Schools XPath Tutorial</a></li><li><a href="https://classic.yarnpkg.com/en/">Yarn</a></li><li><a href="https://code.visualstudio.com/">VS Code</a> — <a href="https://code.visualstudio.com/download">Download Link</a></li><li><a href="https://developers.google.com/web/tools/puppeteer">Puppeteer</a></li><li><a href="https://pptr.dev/#?product=Puppeteer&amp;version=v3.0.0&amp;show=api-class-page">Puppeteer Page documentation</a></li><li><a href="https://nodejs.org/en/">NodeJS</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d4ad1364a75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ramojol/puppeteer-getting-into-coding-with-browser-automation-6d4ad1364a75">Puppeteer: Getting into Coding with Browser Automation</a> was originally published in <a href="https://medium.com/ramojol">ramosly | blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQLAlchemy ORM: Setting Up Self-Referential Many-to-Many Relationships]]></title>
            <link>https://medium.com/ramojol/sqlalchemy-orm-setting-up-self-referential-many-to-many-relationships-866c97d9308b?source=rss----d27fe4c47e7c---4</link>
            <guid isPermaLink="false">https://medium.com/p/866c97d9308b</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Joel Ramos]]></dc:creator>
            <pubDate>Fri, 10 Feb 2017 17:50:18 GMT</pubDate>
            <atom:updated>2018-09-22T21:05:17.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zIsROwXl7-Uopk87LKAa6g.jpeg" /></figure><p>If you’re new to SQLAlchemy, or are trying to get started, this may not be the post for you as I assume some familiarity with Python, SQL, and SQLAlchemy. Perhaps the <a href="http://www.sqlalchemy.org/library.html#tutorials">tutorials section</a> on the package’s <a href="http://www.sqlalchemy.org/">website</a> is a better place to start. SQLAlchemy has proven to be pretty handy once you figure out how to do what you’re trying to do. However, getting there can be a bit challenging, at least it was for me.</p><p>In this post, I will go over one challenge that I recently ran into, and that is how to set up models for database tables with many-to-many relationships to <em>themselves</em>.</p><p>I will assume that you are familiar with relational database concepts and somewhat familiar with Python and SQLAlchemy’s ORM. So, let’s get to it! I’ll start with what the tables look like.</p><h4>The Database Tables</h4><p>Table 1: <strong>Person </strong>table</p><pre>PersonId    PersonType    Name<br>1           Parent        Bob<br>2           Parent        Mary<br>3           Child         Tommy<br>4           Child         Sally</pre><p>Table 2: <strong>ParentChild </strong>(intersect)<strong> </strong>table</p><pre>ParentChildId    ParentId    ChildId<br>1                1           3<br>2                2           3<br>3                1           4<br>4                2           4</pre><p>These tables aren’t exactly the ones I was working with, but they should better illustrate the idea that the Person table has a many-to-many relationship to itself. I.e., one parent can have many children, and one child can have many parents.</p><p>Joining this table to itself to get a child’s parents, or a parent’s children, would look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a249ede36383635a2ce614de70990622/href">https://medium.com/media/a249ede36383635a2ce614de70990622/href</a></iframe><p>At first, it wasn’t clear to me whether SQLAlchemy could handle this scenario, but as it turns out, it can! So, why don’t we take a look at the code first, then I’ll explain.</p><h4>Building the SQLAlchemy Models</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2363c0b64b35aa7c63547897343b774b/href">https://medium.com/media/2363c0b64b35aa7c63547897343b774b/href</a></iframe><h4>Imports</h4><p>If we start at the top, the first 4 lines are just the necessary imports from SQLAlchemy. On the 3rd line, I am just importing the MS SQL Server datatypes provided by SQLAlchemy. You should be able to use those from whatever dialect you are using (e.g., MySQL, Postgres, etc.)</p><h4>Base object</h4><p>Next, in a similar fashion to the documentation, we create a Baseobject via the declarative_base()function. This Baseclass will be the class that our database-table model classes inherit from. For more info, see the <a href="http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#declare-a-mapping">Declare a Mapping</a> section of the documentation.</p><h4>Intersect table</h4><p>After that, we create a variable for the intersect table called parent_child. Interestingly, SQLAlchemy seems to require us to represent intersect tables this way, where we have a variable that we set equal to a Table object which is initialized with the name of the table, the Base.metadata, and then the Column objects. This as opposed to being created like the other tables, which is to say, as classes that subclass the Base object.</p><p>Notice that the two Columns after the primary key column also specify a ForeignKey param, each pointing back to the primary key of the Person table.</p><p><em>Note: Some people might find it confusing that the value you pass to the </em>ForeignKey <em>class must be the table name and column name as they appear in the database, not how you specified them in your Python models. So here, that value is </em>ForeignKey(‘Person.PersonId’)<em>, which is the actual table and column name in the database.</em></p><h4>Table Model class</h4><p>Lastly, the Person class is the model of the database table that we are trying to represent. In this class, we add the required __tablename__ attribute, add Column objects for each column making sure to specify the person_id as the primary key, and finally the relationship.</p><p>For the relationship, we need to add an attribute to the table model class Person to represent the list of foreign objects, which in this case are more Person objects. So, let’s call it parents.</p><p>Next, we set parents equal to SQLAlchemy’s relationship function, which we imported at the top.</p><p>The relationship function takes a variable number of arguments depending on the type of relationship you’re setting up. The first argument to pass is the string name of the foreign table model’s class name. Since we are creating a relationship from Person back to itself, this is just ‘Person’.</p><p>The next argument is a keyword argument called secondary that must be set equal to the intersect-table variable, parent_child.</p><p>In my experience, this is all that would be required for your average many-to-many relationship, but for our case, we also need to specify the primaryjoin and secondaryjoin keyword arguments so that SQLAlchemy knows what to do with the two ForeignKey columns in our intersect-table variable. And this makes sense if you were to recreate the join order in SQL, which I suggest doing so that you have a clear picture of the relationships you’re trying to represent.</p><p><em>Note: for anyone reading this that might be new to SQLAlchemy and has made it this far, everything described above only pertains to setting up the table models, and does not touch on how to execute queries against them using the ORM syntax. For that, I would check out the </em><a href="http://docs.sqlalchemy.org/en/latest/orm/tutorial.html"><em>Object Relational Tutorial</em></a><em>.</em></p><h4>Conclusion</h4><p>Usually, I find myself linking one table model to another via a one-to-many relationship, or many-to-one, with the occasional many-to-many relationship via an intersect table. This case was unusual for me, as I needed to link the table to itself as a many-to-many relationship.</p><p>However, each time I’ve come across an edge-case, SQLAlchemy has had something to support that scenario. It can take a bit of hunting to find the solution in the documentation, though, so I thought I’d document this one here just in case I need to come back to it, or someone else finds it useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=866c97d9308b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ramojol/sqlalchemy-orm-setting-up-self-referential-many-to-many-relationships-866c97d9308b">SQLAlchemy ORM: Setting Up Self-Referential Many-to-Many Relationships</a> was originally published in <a href="https://medium.com/ramojol">ramosly | blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>