Thursday, April 26, 2018

Python - how to make a mock return a different result the second time it's called

Problem
I am testing a function that has a loop that only stops when an element on a webpage is not found. So i need a mock to do different things on different iterations of the loop.

Solution
This is done by setting the side_effect as a list.

When find_element_by_css_selector is called, it will do the following:
loop iteration 1 - it'll pass back mockElement
loop iteration 2 - it'll throw an exception (this is what selenium does if the element is not found, so i'm just simulating that)


    @mock.patch("selenium.webdriver.chrome.webdriver.WebDriver")
    @mock.patch("selenium.webdriver.remote.webelement.WebElement")
    def test_whenButtonExists_weclickit(self, mockBrowser, mockElement):
        #arrange
        cmd = Cmd();
        cmd.browser = mockBrowser
        mockBrowser.find_element_by_css_selector.side_effect = [mockElement, Exception()]

        #act
        data = cmd.getDataFromWebsite()

        #assert
        mockElement.click.assert_called()

Sunday, April 22, 2018

Mocking in Python

How do I mock in Python?

Here's how:

the key is to import unittest.mock, and then add the @mock.patch decorator to the unit tests where you want to use a mock object. This causes it to pass a mock object in.

In the second test below, notice that i am causing the mock object to throw an exception.


from unittest import TestCase, mock
from Commander import Commander
from Command import Command

class CommanderTests(TestCase):

    @mock.patch("Command.Command")
    def test_whenrunAll_commandIsRan(self, mockCmd):
        #arrange
        commander = Commander();
        commander.addCommand(mockCmd);

        #act
        commander.runAll();

        #assert
        mockCmd.run.assert_called();

    @mock.patch("Command.Command")
    def test_whenrunAll_andCommandThrowsException_ExceptionDoesNotBubble(self, mockCmd):
        #arrange
        commander = Commander();
        mockCmd.run.side_effect = Exception();
        commander.addCommand(mockCmd);

        #act
        commander.runAll();

        #assert
        mockCmd.run.assert_called();

Saturday, March 24, 2018

Create shortcut to run python script from Notepad++

1. Run
2. Type cmd /C cd /d $(CURRENT_DIRECTORY) && python -i "$(FULL_CURRENT_PATH)" 
3. Click Save...
4. Choose a key combo, like Ctrl+F5
5. Click OK

Now you can press the shortcut to run your current script

Tuesday, March 20, 2018

Simulate key press event in Chrome

This is the correct way to send key events in chrome


Code:
var e = document.createEvent("Event")
e.initEvent("keydown",true,true)
e.keyCode = 38
e.which = 38

window.document.dispatchEvent(e)

Note: 38 = up arrow

Ref:

http://jsbin.com/awenaq/3

Searched for:
1. keyboardEvent code is empty
2. Chrome simulate key press

Tuesday, March 13, 2018

Paint in Raspberry Pi

Problem
I need to be able to create image files in Raspberry Pi (raspbian)

Solution
1. Install xpaint
  • sudo apt install xpaint

2. Open from the menu
  • 1. Pi button
  • 2. Graphics
  • 3. Xpaint

Sunday, March 11, 2018

how to make it so git doesn't prompt for password

Problem:
Every time I push in git I have to enter my password, and I don't want to



Solution
1. ssh-keygen -t rsa -b 4096

Note: to avoid entering a password when I push, I left the password blank here. 
2. cat ~/.ssh/id_rsa.pub | xclip -sel clip
Note: I didn't have xclip, so I had to install like this >> sudo apt install xclip
3. Add the key here https://bitbucket.org/account/user/<username>/ssh-keys/
4. Clone using this: git clone git@bitbucket.org:<username>/<reponame>.git


Environment
1. Raspbian OS on raspberry Pi
2. Using git with Bitbucket

Sunday, February 4, 2018

Sync over Async anti-pattern in C#

Problem
I was working on optimizing some code at work. This code was calling PostAsync to a web service. The problem was that Task.Wait() was used. This is called the Sync over Async anti-pattern, and causes a blocking wait. This basically means that thread is wasted, and could be causing unresponsiveness (like your UI freezing, depending on where you called it from)

Note: This also happens if you try to use the Task.Result right after the async call.

Here's an example:
        //Bad
        public string GetWeatherData_SyncOverAsync_Wait(string City)
        {
            var http = new HttpClient();
            var url = $"http://api.openweathermap.org/data/2.5/weather?q={City}&APPID={key}";

            var responseTask = http.GetAsync(url);
            responseTask.Wait();
            responseTask.Result.EnsureSuccessStatusCode();
            var contentTask = responseTask.Result.Content.ReadAsStringAsync();
            contentTask.Wait();
            string responseData = contentTask.Result;
            return responseData;
        }


Solution
await the Task. This releases the thread back to the threadpool until the task completes.

Step 1 - Put async in the method signature.

Step 2 - Make your method return a Task<T>.

Step 3 - await the async call

Step 4 - You will have to repeat these steps in the caller too, and that caller's callers. Basically you need async/await all the way up

        //Good
        public async Task<string> GetWeatherDataAsync(string City)
        {
            var http = new HttpClient();
            var url = $"http://api.openweathermap.org/data/2.5/weather?q={City}&APPID={key}";

            var responseTask = await http.GetAsync(url);
            responseTask.EnsureSuccessStatusCode();
            string responseData = await responseTask.Content.ReadAsStringAsync();
            return responseData;
        }


There was an error in this gadget