<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Viktor Maksymenko on Medium]]></title>
        <description><![CDATA[Stories by Viktor Maksymenko on Medium]]></description>
        <link>https://medium.com/@viktormaksimenko?source=rss-e5337058bb09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rlYYnV7OsLF8-ppIV87krw@2x.jpeg</url>
            <title>Stories by Viktor Maksymenko on Medium</title>
            <link>https://medium.com/@viktormaksimenko?source=rss-e5337058bb09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 06:37:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@viktormaksimenko/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Блеск и Нищета Cypress.io]]></title>
            <link>https://medium.com/@viktormaksimenko/%D0%B1%D0%BB%D0%B5%D1%81%D0%BA-%D0%B8-%D0%BD%D0%B8%D1%89%D0%B5%D1%82%D0%B0-cypress-io-40dc50743026?source=rss-e5337058bb09------2</link>
            <guid isPermaLink="false">https://medium.com/p/40dc50743026</guid>
            <category><![CDATA[testing-tools]]></category>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[automation-tools]]></category>
            <dc:creator><![CDATA[Viktor Maksymenko]]></dc:creator>
            <pubDate>Wed, 18 Dec 2019 12:46:36 GMT</pubDate>
            <atom:updated>2020-07-08T19:24:53.575Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Дисклаймер</strong>: данная статья содержит исключительно мое мнение о Cypress.io, а так же пережитые боль и слезы. Она не ставит за цель выставить в дурном свете продукт или команду которая над ним трудится, это только мой опыт.</p><p>Статья будет дополняться в процессе получения новых знаний и, в целом, должна начинаться фразой “Дорогой дневник…”</p><figure><img alt="Francesco Bianchi, Arion Riding on a Dolphin" src="https://cdn-images-1.medium.com/max/643/1*frKjjKnelYYuA8uD3O2Mwg.jpeg" /></figure><p><a href="https://www.cypress.io/">Cypress.io</a> — безусловно няшка. И сайт красивый, и дебаггер свой, умный, и прогоны в облаке хранит, и ставится одной командой, и запускается в браузере, уйма интеграций, одни плюсы. Пока вы не начинаете с ним работать. Вот пара вещей, на которые я натолкнулся.</p><h4>1. Ограничения Cypress</h4><p>Cypress запускается только в Chrome и Electron . И только в одной сессии. Такой уж у них дизайн и ничего с этим не сделаешь. Вроде бы поддержка Firefox есть у них в <a href="https://docs.cypress.io/guides/references/roadmap.html#Upcoming-features">Roadmap</a>, но когда оно будет — неизвестно. Еще на количество записей в Cypress Dashboard тоже есть ограничение, но это тоже выглядит честно, ребятам надо на что-то жить. Меня эти ограничения не смутили и Cypress был взят в работу.</p><h4>2. Мыслим асинхронно</h4><p>Если вы хотите после работы на Java/Python взять в проект (не просто попробовать) Cypress, то лучше нет. Серьезно, берите WebDriver.IO или любой его аналог, но не Cypress. Он беспринципно асинхронный. И работает только со своими Promise. Которые просто методы, которые принимают колл-бек. Как следствие, машем ручкой async-await и Promise.all. Для последнего к счастью нашелся аналог на <a href="https://stackoverflow.com/questions/58285668/gather-results-from-multiple-cypress-promisses/58300534#58300534">StackOverflow</a>, который умеет принимать N Cypress объектов и работать с ними. Почему этого еще нет в их API — вопрос риторический.</p><h4>3. Мыслим еще асинхронее</h4><p>Собственно необходимость в том, чтобы передавать несколько Promise в один метод появилась тогда, когда пришлось проверять несколько текстовых полей на одной странице. И тут открылось еще кое-что страшное: у Cypress нет метода, который бы вытащил текст из элемента, есть только вот такой <a href="https://docs.cypress.io/faq/questions/using-cypress-faq.html#How-do-I-get-an-element%E2%80%99s-text-contents">FAQ article</a>, который советует вызывать JQuery метод text, потом вызвать метод then и уже в него передать обработчик.</p><pre><strong><em>cy</em></strong>.get(&#39;div&#39;).invoke(&#39;text&#39;).then((text1) =&gt; {<br><br>  // grab the div again and compare its previous text<br>  // to the current text<br>  <strong><em>cy</em></strong>.get(&#39;div&#39;).invoke(&#39;text&#39;).should((text2) =&gt; {<br>    expect(text1).not.to.eq(text2)<br>  })<br>})</pre><p>Таким образом, если у вас на странице есть элементы A, B и Sum, то вам нужно делать 3 вложенные функции, чтобы проверить, что A + B = Sum. Мне показалось, что это уже перебор, и тогда-то и была найдена кастомная команда cy.all, которая была целиком скопирована в проект. С ней получилось реализовать проверку вот так:</p><pre><strong><em>cy</em></strong>.all(<br>  <strong><em>cy</em></strong>.get(&#39;.a&#39;).invoke(&#39;text&#39;),<br>  <strong><em>cy</em></strong>.get(&#39;.b&#39;).invoke(&#39;text&#39;),<br>  <strong><em>cy</em></strong>.get(&#39;.sum&#39;).invoke(&#39;text&#39;),<br>).then(([ textA, textB, textSum ]) =&gt; {<br>  /* ... */<br>});</pre><h4>4. Абсолютная асинхронность</h4><p>Если вы любите Page Object Pattern, то будьте готовы к тому, что Cypress его не любит. По крайней мере в моем случае (Cypress + Cucumber Preprocessor) сделать все просто и привычно не вышло. Хотите вызывать цепочки методов — оборачивайте их в степы, которые возвращают Cypress коллбек или null. Иначе получите ошибку при определении Cucumber степа</p><pre>CypressError: cy.then() failed because you are mixing up async and sync code.</pre><p>Не знаю, проблема ли это Cypress или Cucumber, но факт остается фактом.</p><h4>5. Забудьте про цикл for</h4><p>Сypress асинхронный, помните? Так что Array.forEach и старый-добрый for не отработают. Делаем cy.wrap({a: 5}).each(e =&gt; cy.log) и вот так уже можно итерировать.</p><h4>5. Версии</h4><p>Тут в двух словах: обновился с версии 3.7.0 до 3.8.0, и на странице логина перестал вводится текст в input. А точнее, конкретный текст — “000123456”. Откатился обратно к 3.7.0 — и все снова заработало. Magic!</p><h4>6. Репорты</h4><p>Если вы привыкли к удобным репортам, которые показывают каждый степ и экшины в нем (например, Allure Reports), то, да-да, снова забудьте. Да, у Cypress есть дашборд. Да, можно добавить к фреймворку репортеры Mocha ( возможно даже Allure для Mocha, но это не точно). Но если вы пишете кастомные степы или используете Cucumber Preprocessor, то степов у вас в условном Mochawesome репорте не будет, только название теста и статус. Для Cucumber — еще код, который похоже вызывается при трансляции Gherkin в код. Не самый информативный вывод, 2 из 10.</p><h4>7. Пара слов о коммьюнити</h4><p>Чат <a href="https://gitter.im/cypress-io/cypress">Cypress в Gitter</a> — удивительно открыт к помощи и может сильно выручить. Другой вопрос — их <a href="https://github.com/cypress-io/cypress/issues">GitHub репо</a>, в котором issues могут жить вечность. Будьте готовы к тому, что у их саппорт инженера не воспроизведется, в ее браузере все будет ок и вообще “у меня напротив такое же здание, и оно не горит”. А вот от нее иногда неплохо так полыхает.</p><p>Итого, мой вывод прост: Cypress и правда во многом хорош и удобен, но далеко не всегда тривиален, и к этому нужно быть готовым. Он требует понимания возможностей JS и, нередко, напильника. Если вы готовы к этому, то Welcome!</p><p>На этом пока все, продолжение следует (но хочется верить, что новых пунктов не будет).</p><h3>UPD: 08.07.2020</h3><p>Видит Бог, я этого не хотел. На дворе 2020 год, Cypress выпустил версию 4.10.20, некоторые пункты статьи устарели, но зато я открываю для себя новые грани чудесного тестового фреймворка.</p><h4>8. Никакого Error-handling’а</h4><p>В документации есть большая и красивая статья о том, что <a href="https://docs.cypress.io/guides/core-concepts/conditional-testing.html#Error-Recovery">try-catch — это плохо</a>. Не стану спорить с авторами, озвучу только ситуацию, с которой довелось столкнуться. У Cypress есть метод <em>request</em>, который, как можно догадаться, делает запросы. Представьте себе, что вы в вашем тесте проверяете, что пользователь может удалить свой аккаунт. И выполняете его через API. Удаление проходит успешно, а дальше вы пробуете зайти в систему с данными удаленного пользователя. Запрос честно падает с кодом 40х, и вместе с ним падает и тест. Хотя должен быть пройден. И как с этим бороться я пока не знаю.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40dc50743026" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to catch HTTP traffic in Appium automated tests with BrowserMob MITM proxy]]></title>
            <link>https://medium.com/@viktormaksimenko/how-to-catch-http-traffic-in-appium-automated-tests-with-browsermob-mitm-proxy-eb8e85b5ba7d?source=rss-e5337058bb09------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb8e85b5ba7d</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[appium]]></category>
            <category><![CDATA[http-proxy]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[automated-testing]]></category>
            <dc:creator><![CDATA[Viktor Maksymenko]]></dc:creator>
            <pubDate>Sat, 17 Aug 2019 13:19:26 GMT</pubDate>
            <atom:updated>2019-08-19T05:37:24.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgMP5DihSlb2K8As7T_QXg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@maguay?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Matthew Guay</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>BrowserMob proxy (BMP) is very popular in terms of browser UI automated testing. It can simplify checks and even speed up the test runs by filtering redundant requests. But there’s a lack of information about its usage in mobile automated testing. So, here we’re trying to fix it and show, how to catch HTTP requests from iOS and Android devices in Appium tests. As far as it’s easier to build and compile Android app we’re using it as our app under test. But for iOS, BMP will work the same, the only difference will be in the device configuration.</p><h3>What is the BrowserMob Proxy?</h3><p>According to <a href="https://github.com/lightbody/browsermob-proxy">BrowserMob readme</a>:</p><blockquote>BrowserMob Proxy allows you to manipulate HTTP requests and responses, capture HTTP content, and export performance data as a <a href="http://www.softwareishard.com/blog/har-12-spec/">HAR file</a>. BMP works well as a standalone proxy server, but it is especially useful when embedded in Selenium tests.</blockquote><p>Next, we’ll show how to use it in Appium tests. We’ll set up a Java testing framework that will get, validate and update requests and responses from Android device. For iOS, it will work the same way, except proxy setup. At the end of the article, we’ll discuss the usage of BMP with emulators and cloud providers.</p><h3>Framework Development</h3><p>As a test app, we’ll use the final app from <a href="https://www.raywenderlich.com/2-android-networking-tutorial-getting-started">Android Networking Tutorial</a>. It lists GitHub repositories found by “kotlin” query. You may download the .apk file from <a href="https://www.dropbox.com/s/b4p1uqm24vk2vn7/app-debug.apk?dl=0">Dropbox</a>.</p><p>Next, we’ll create a maven project with TestNG testing framework to run Appium tests. For simplifying work with selector and other selenium harnesses we’ll use Selenide. You may find the configured project on <a href="https://github.com/vikmaksimenko/browsermob-appium-sample">GitHub</a></p><p>Please, update the DEVICE_NAME<em> </em>capability in src/test/java/browsermob_sample/SampleBrowsermobTest.java<em> </em>with your device name before running tests. To run the test, call</p><pre>mvn clean test</pre><p>It will start Appium service, install and open the app and check if project “JetBrains/kotlin” is in the list. Next, we’ll work on Browsrmob integration, so you may checkout to commit e09709f<em> </em>and do other code changes by yourself.</p><h3>Android Device Config</h3><p>For device configuration, we need to perform the following steps:</p><ul><li>Install CA certificate</li><li>Configure proxy</li><li>Configure the test app to allow proxy</li></ul><h4>Install CA Certificate</h4><ul><li>Download CA certificate from <a href="https://github.com/lightbody/browsermob-proxy/blob/master/browsermob-core/src/main/resources/sslSupport/ca-certificate-rsa.cer">BMP repo</a></li><li>Copy the ca-certificate-rsa.cer to the root of the /sdcard folder inside your Android device</li><li>Inside the device, Settings &gt; Security &gt; Install from storage</li><li>Select ca-certificate-rsa.cer from storage</li><li>(Optional) Before you install the certificate, the PIN might be prompted. You’ll have to create one or use the existing.</li></ul><h4>Configure proxy</h4><ul><li>Verify, that proxy host and device are in the same network</li><li>Get proxy host IP</li><li>Go to device’s settings and wifi configuration</li><li>Press and hold on the network you’re going to use and select Modify network from the alert modal</li><li>Then check Advanced Options and scroll until you see Proxy</li><li>Tap the Proxy dropdown and select Manual</li><li>For the Proxy hostname input your proxy’s IP address</li><li>Then for the Proxy port use <em>8888. </em>We’ll set it later in BrowserMob proxy config</li><li>Tap Save</li></ul><h4>Configure the test app</h4><ul><li>Specify the res/xml/network_security_config.xml file in Android app</li><li>Update AndroidManifest.xml to use network_security_config</li><li>Rebuild app</li></ul><h3>Configuring framework to use BMP</h3><p>So, now we should have the device prepared for testing. Let’s set up our testing framework to create a proxy server and interact with app responses!</p><p>As far as Selenide loads BrowserMob proxy as a dependency we don’t need to ad BMP to our pom.xml. So let’s create BrowserMobHelper.class in utils directory. We’ll make it a singleton, so there’ll be only one instance of proxy during the run.</p><pre>package browsermob_sample.utils;</pre><pre>import net.lightbody.bmp.BrowserMobProxy;<br>import net.lightbody.bmp.BrowserMobProxyServer;<br>import net.lightbody.bmp.core.har.Har;<br>import net.lightbody.bmp.proxy.CaptureType;</pre><pre>public class BrowserMobHelper {<br>    private static BrowserMobHelper <em>ourInstance </em>= new BrowserMobHelper();<br>    private static BrowserMobProxy <em>proxy</em>;</pre><pre>public static BrowserMobHelper getInstance() {<br>        if(<em>proxy </em>== null) {<br>            <em>proxy </em>= new BrowserMobProxyServer();<br>            <em>proxy</em>.start(8888);<br>            System.<em>out</em>.println(&quot;=== Proxy has been started ===&quot;);<br>        }<br>        return <em>ourInstance</em>;<br>    }</pre><pre>public void stopProxy() {<br>        if(<em>proxy </em>!= null) {<br>            <em>proxy</em>.stop();<br>            <em>proxy </em>= null;<br>            System.<em>out</em>.println(&quot;=== Proxy is stopped ===&quot;);<br>        }<br>    }<br>}</pre><p>Now we can add proxy management methods to setup and teardown methods of SampleBrowsermobTest</p><pre>...</pre><pre>public class SampleBrowsermobTest {</pre><pre>private AppiumDriverLocalService appiumService;<br>    private BrowserMobHelper bmpHelper = BrowserMobHelper.<em>getInstance</em>();</pre><pre>...</pre><pre>@AfterMethod(alwaysRun = true)<br>    public void tearDown(ITestResult result) throws IOException {<br>        bmpHelper.stopRecording().writeTo(new File(&quot;sample.har&quot;));<br>        bmpHelper.stopProxy();<br>        appiumService.stop();<br>    }<br>}</pre><p>Finally, run test. It should be ok. This we’ll indicate, that proxy is configured well. If the test fails and GitHub repo list is not displayed then check your proxy config.</p><h3>Working with requests</h3><p>So, now the proxy is a part of our test framework, but we do not interact with requests, that go throw it. Let’s see, how we can view and modify requests and responses.</p><h4>Record query</h4><p>For recording requests and responses, let’s add 2 more methods: startRecording and stopRecording.</p><pre>public BrowserMobHelper startRecording() {<br>    <em>proxy</em>.enableHarCaptureTypes(CaptureType.<em>REQUEST_CONTENT</em>, CaptureType.<em>RESPONSE_CONTENT</em>);<br>    <em>proxy</em>.newHar();<br>    return this;<br>}</pre><pre>public Har stopRecording() {<br>    if(<em>proxy</em>.getHar() != null) {<br>        return <em>proxy</em>.endHar();<br>    }<br>    return null;<br>}</pre><p>Next, let’s update our test to save HAR. We’ll call startRecording in the setup method and write tracked requests and responses to sample.har file in the teardown method.</p><pre>...</pre><pre>@BeforeMethod<br>public void setup() {<br>    bmpHelper.startRecording();</pre><pre>... <br>}</pre><pre>...</pre><pre>@AfterMethod(alwaysRun = true)<br>public void tearDown() throws IOException {<br>    bmpHelper.stopRecording().writeTo(new File(&quot;sample.har&quot;));<br>    bmpHelper.stopProxy();<br>    appiumService.stop();<br>}</pre><p>So, now we can rerun the test, open HAR file and review all the requests, that were sent during the test. This version of the testing framework is stored in this <a href="https://github.com/vikmaksimenko/browsermob-appium-sample/commit/ffdd4e764baff4e95b720ab42d6dcbb9402fa504">commit</a>.</p><h4>Overwriting Response</h4><p>Let’s now overwrite the response from GitHub. There are 4 methods to support request and response interception:</p><ul><li>addRequestFilter</li><li>addResponseFilter</li><li>addFirstHttpFilterFactory</li><li>addLastHttpFilterFactory</li></ul><p>See more details in “<a href="https://github.com/lightbody/browsermob-proxy#http-request-manipulation">HTTP Request Manipulation</a>” section of BMP docs. For demo purposes, we’ll use addResponseFilter. Let’s add a method overrideGitHubResponse to BrowserMobHelper so replace word <strong>kotlin </strong>with word <strong>shmotlin</strong></p><pre>public BrowserMobHelper overrideGitHubResponse() {<br>    proxy.addResponseFilter((response, contents, messageInfo) -&gt; {<br>        if (messageInfo.getUrl().contains(&quot;https://api.github.com/search/repositories&quot;)<br>                &amp;&amp; messageInfo.getUrl().contains(&quot;kotlin&quot;)) {<br>            contents.setTextContents(contents.getTextContents().replace(&quot;kotlin&quot;, &quot;shmotlin&quot;));<br>        }<br>    });</pre><pre>return this;<br>}</pre><p>Then, we’ll update the test to do response overwrites. It should check that <strong>JetBrains/kotlin </strong>is not on the list, but <strong>JetBrains/shmotlin </strong>presents.</p><pre>@BeforeMethod<br>public void setup() {<br>    bmpHelper.overwriteGitHubResponse().startRecording();<br>    <br>    ...<br>}</pre><pre>@Test()<br>@Description(&quot;JetBrains Kotlin shouldn&#39;t be in list, if response is overwritted&quot;)<br>public void jetBrainsKotlinShouldNotBeInListIfResponseIsOverwritted() {<br>    <em>$</em>(By.<em>id</em>(&quot;com.raywenderlich.githubrepolist:id/refreshButton&quot;)).shouldBe(<em>visible</em>).click();<br>    <em>$x</em>(&quot;//android.widget.TextView[@resource-id=&#39;com.raywenderlich.githubrepolist:id/repoName&#39; and @text=&#39;JetBrains/shmotlin&#39;]&quot;)<br>            .waitUntil(<em>exist</em>, 30 * 1000).shouldBe(<em>visible</em>);<br>    <em>$x</em>(&quot;//android.widget.TextView[@resource-id=&#39;com.raywenderlich.githubrepolist:id/repoName&#39; and @text=&#39;JetBrains/kotlin&#39;]&quot;)<br>            .shouldNot(<em>exist</em>);<br>}</pre><p>Run test. It should also pass. This version of the framework is stored in this <a href="https://github.com/vikmaksimenko/browsermob-appium-sample/commit/a082e5447ad10824b6bd4dba7f715b3af8ce2ad5">commit</a>.</p><p>It’s not a full list of BMP features, so go on and investigate its docs and sources in the <a href="https://github.com/lightbody/browsermob-proxy">repo</a></p><h3>Working with Emulators and Cloud Providers</h3><p>There are two concerns of using BMP (or any other proxy) with emulators and cloud providers:</p><ol><li>Proxy and device should be on the same network</li><li>For setting MITM you need to install proxy’s CA certificate</li></ol><p>For emulators, you can install CA, but need to figure out the network staff. I tried setting up Android emulators with BMP, but HTTPS proxy didn’t work for me (if you were able to set it up please leave a response). Probably, the reason is in the way of handling a network. The emulator does not connect directly to your network, so it can’t resolve proxy server address. However, if you still need to use BMP with emulators, <a href="https://www.genymotion.com/">Genymotion</a> may help you. It allows to set network bridge, so Genymotion emulator will behave as a member of your network and BMP will work properly</p><p>For Cloud Providers, the main concern is a need of installing custom certificates. I checked a few providers and here are my results:</p><ul><li><a href="https://aws.amazon.com/device-farm/"><strong>AWS Device Farm</strong></a><strong> — </strong>HTTP Proxy is not supported — <a href="https://forums.aws.amazon.com/message.jspa?messageID=762945">https://forums.aws.amazon.com/message.jspa?messageID=762945</a></li><li><a href="https://www.browserstack.com/"><strong>BrowserStack</strong></a> — Also no HTTP Proxy support</li><li><a href="https://firebase.google.com/docs/test-lab/"><strong>Firebase Test Lab for Android</strong></a><strong> </strong>— Haven’t found info about HTTP proxy</li><li><a href="https://appcenter.ms/"><strong>Visual Studio App Center</strong></a> — Also nothing about HTTP proxy, even less documented than Firebase</li><li><a href="https://saucelabs.com/"><strong>SourceLabs</strong></a> — Have support for BMP, described in <a href="https://wiki.saucelabs.com/display/DOCS/Sauce+Connect+Proxy+with+an+Additional+Proxy+Setup">docs</a>, but they do not allow the possibility of installing custom certificates for security reasons</li><li><a href="https://kobiton.com/"><strong>Kobiton</strong></a> — Haven’t found info in docs, asked a support team. If you’re using their private devices Kobiton team can allow installation of custom certificates</li><li><a href="https://www.perfecto.io/"><strong>Perfecto</strong></a> — seems that it can be used with Charles Proxy — <a href="https://developers.perfectomobile.com/display/PD/Using+a+bridging+proxy">https://developers.perfectomobile.com/display/PD/Using+a+bridging+proxy</a>. On the other hand, looks like it has few devices. Also, I failed to install my test.apk file to Perfecto devices, so haven’t completed the investigation</li></ul><p>So, it was complicated for me to configure BMP with cloud providers. If you’ve succeeded, please share your story.</p><h3>Conclusion</h3><p>So, here we were able to integrate BMP into Appium Java testing framework. I hope this article was helpful. Also, BMP is not the only proxy tool, for instance, you may use <a href="https://mitmproxy.org/">mitmproxy</a>’s Python API or write a wrapper to its command-line tool. Similiar you may use <a href="https://www.charlesproxy.com/">Charles Proxy</a> command-line API. Maybe you know other tools and methods of proxying device responses, so feel free to share your solutions and thoughts. Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb8e85b5ba7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Doing time shift without changing system time with libfaketime and Mockdate]]></title>
            <link>https://medium.com/@viktormaksimenko/doing-time-shift-without-changing-system-time-with-libfaketime-and-mockdate-869d54f5c8a1?source=rss-e5337058bb09------2</link>
            <guid isPermaLink="false">https://medium.com/p/869d54f5c8a1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Viktor Maksymenko]]></dc:creator>
            <pubDate>Tue, 30 Jul 2019 05:40:44 GMT</pubDate>
            <atom:updated>2019-07-30T14:42:19.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68fPZL6QCXC19wgqi32-MA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@loic?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Djim Loic</a> on <a href="https://unsplash.com/search/photos/time?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Sometimes your application is doing something according to current date and time (like annual payment, etc.). To validate it, you have to change system time, but often it’s complex or even impossible task. When you’re running your tests with cloud providers or in containers, you can’t disable time sync services. In this case, the <a href="https://github.com/wolfcw/libfaketime">libfaketime</a> can become a solution.</p><h3>Libfaketime</h3><p>This is how it works (from its description):</p><blockquote>libfaketime intercepts various system calls that programs use to retrieve the<br>current date and time. It then reports modified (faked) dates and times (as<br>specified by you, the user) to these programs. This means you can modify the<br>system time a program sees without having to change the time system-wide.</blockquote><p>Let’s try it! First, we’ll create a simple app called “is_it_christmass.js”. It will check if it’s the 25th of December now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0534f5ce528877aeb1b7ecb61d48e0bc/href">https://medium.com/media/0534f5ce528877aeb1b7ecb61d48e0bc/href</a></iframe><p>So, let’s say you want to run this script by schedule every morning. And want to test it before deployment to the server. It’s not an option to wait for a year for a single test. So, it’s time for libfaketime.</p><ol><li>Clone libfaketime <a href="http://git@github.com:wolfcw/libfaketime.git">repo</a></li><li>Run <strong>make</strong></li><li>(Optional) Run <strong>sudo make install </strong>to place *.so files in <em>/usr/local/lib/faketime</em><br>and install the wrapper shell script “faketime” in <em>/usr/local/bin</em></li></ol><p>Now, let’s verify lib and its wrapper</p><pre>root@1431a2c5a142:/libfaketime# date</pre><pre>Mon Jul 29 18:40:55 UTC 2019</pre><pre>root@1431a2c5a142:/libfaketime# LD_PRELOAD=/usr/local/lib/faketime/libfaketime.so.1 FAKETIME=”-15d” date</pre><pre>Sun Jul 14 18:41:00 UTC 2019</pre><pre>root@1431a2c5a142:/libfaketime# faketime ‘last Friday 5 pm’ date</pre><pre>Fri Jul 26 17:00:00 UTC 2019</pre><p>And let’s try to use it with our script</p><pre>root@1431a2c5a142:/# node is_it_christmass.js</pre><pre>It’s not a Christmas yet =(</pre><pre>root@1431a2c5a142:/# faketime “25 Dec” node is_it_christmass.js</pre><pre>It’s Christmas!</pre><p>Let’s go further, and init NPM project and cover our function with spec tests:</p><ol><li>Do<strong> npm init </strong>in the script directory</li><li>Update the script to wrap function into a module. Require it from <strong>index.js</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2ba1b6ae1192556d27c543890e91c45/href">https://medium.com/media/f2ba1b6ae1192556d27c543890e91c45/href</a></iframe><p>3. Install Jasmine</p><pre>npm install jasmine</pre><pre>$(npm bin)/jasmine init</pre><p>4. Create <strong>spec/is_it_christmass.spec.js </strong>and update <strong>package.json</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/049892b7000e8d03410d8d481a759d99/href">https://medium.com/media/049892b7000e8d03410d8d481a759d99/href</a></iframe><p>5. Run tests with <strong>npm test </strong>— one should fail.</p><p>According to libfaketime docs, for changing system time from the test, we’ll just need to update $FAKETIME variable with the required date from the test context and it should do the trick. But… no. For me npm does not work with LD_PRELOAD and the command freezes (please, response me, if you know how to run it properly). Luckily, there’s another solution for Node — <a href="https://www.npmjs.com/package/mockdate">Mockdate</a> module</p><h3>Mockdate</h3><p>Perform the following:</p><ol><li><strong>npm install -s mockdate</strong></li><li>Update <strong>is_it_christmass_module.spec.js</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e98fd6b08f74a8e81e64b9fd2761cd9e/href">https://medium.com/media/e98fd6b08f74a8e81e64b9fd2761cd9e/href</a></iframe><p>3. Run specs with <strong>npm test</strong></p><p>Tests should pass now.</p><h3>Conclusion</h3><p>Here we briefly observed 2 ways for faking date and time — with libfaketime and MockDate module. The first one is more general because it replaces system DateTime functions, the second one just overrides the JavaScript Date object. I assume there are some other ways to fake the system date so feel free to share your “wibbly wobbly time-y wimey stuff” in responses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=869d54f5c8a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>