lundi 29 juillet 2019

Python Mocking the postgres database

MagicMock name='con.cursor.fetchall' id='a121213312' I want to have value when I call read function

db.py

try:
    con = psycopg2.connect(
                    host="yhvh",
                    database="python_db",
                    user="postgres",
                    password="ichoose",
                    )
except:
    print("Unable to connect database")

# Open a cursor to perform database operation
cur = con.cursor()

def read(con):
    """
    Read data in Database
    """
    print("Read")
    cur = con.cursor()

    # execute the query
    data ="SELECT id, name FROM employees"
    cur.execute(
        data
    )
    # fetchall - returns all entries
    rows = cur.fetchall()

    for r in rows:
        print(f"id {r[0]} name {r[1]}")

    return rows


test_db.py

class TestDb(unittest.TestCase):
    """
    Study
        - Mock and Unittes
    """
    def test_read(self):
        expected = (9, 'jibreel')

        with patch("db.con") as mock_connect:
            mock_con = mock_connect.return_value
            mock_cur = mock_con.cursor.return_value
            mock_cur.fetchall.return_value = expected

            result = db.read(mock_connect)
            print(result)
            self.assertEqual(result, expected)



The error when I test it

AssertionError: MagicMock name='con.cursor.fetchall' id='a121213312' != (9, 'jibreel')

dimanche 28 juillet 2019

How can i get/ mock activity while implementing instrumented tests?

I'm trying to implement a test which requires activity as parameter, and i can't find a way to mock activity.

For example, whenever i need context in a test i usually use:

Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();

But can't find something similar for activity. Any idea?

How to run a load test using Jmeter while Fiddler is running?

I want to execute a load test using Jmeter while Fiddler is recording the transactions that is currently happening. How do I do it? And is it possible to send the fiddler trace log during my jmeter test execution? Thank you.

How to test a library against different Python *patch* versions?

I'm writing a library and want to test against different Python patch versions, like 3.7.1, 3.7.2, etc

I've been using tox for a long time, however, according to this answer, it doesn't really support this kind of usage.

Any suggestions?

How can I properly test my React Native OAuth wrapper component?

I have written a React Native "Auth Portal" component, that links with an existing OAuth portal and handles getting the auth-code from the redirect URI and the subsequent token exchange request. It seems to be working well, but clearly I need to test this assumption, so I am trying to write unit/functional tests. How can I properly do this?

I originally considered extracting the functions used in the two useEffects out into separate, isolated functions and taking, for example, the authCode as an argument instead of from state and mocking this input.

However, I believe a better strategy is to test the component as a whole and just mock the response to the axios post request, comparing that mock to what get's stored in the AsyncStorage, as well as mocking a bad request/response to test the error handling.

Is this a good approach?

import axios from 'axios'
import AsyncStorage from '@react-native-community/async-storage'
import React, { useEffect, useState } from 'react'
import { Linking } from 'react-native'
import InAppBrowser from 'react-native-inappbrowser-reborn'
import { LoadingIndicator } from '../LoadingIndicator'

interface AuthPortalProps {
    client_id: string
    scopes: string[]
    client_secret: string
    redirect_uri: string
    onAuthComplete: () => void
    onError: () => void
}

interface ApiDataResponse {
    token_type: string
    expires_in: number
    access_token: string
    refresh_token: string
}

export const AuthPortal = ({
    client_id,
    scopes,
    client_secret,
    redirect_uri,
    onAuthComplete,
    onError,
}: AuthPortalProps) => {
    const [authCode, setAuthCode] = useState()

    const getAuthCodeFromRedirectUri = async (url: string) => {
        if (url.includes('code=')) {
            const regex = /[^=]+$/g
            const code = url.match(regex)!.toString()

            await setAuthCode(code)
        }
    }

    useEffect(() => {
        const getAuthCode = async () => {
            const url = `https://example.com/auth/?response_type=code&client_id=${client_id}&redirect_uri=${redirect_uri}&scope=${scopes}`

            if (!authCode) {
                try {
                    InAppBrowser.openAuth(url, redirect_uri).then(response => {
                        if (response.type === 'success' && response.url && response.url.includes('code=')) {
                            getAuthCodeFromRedirectUri(response.url)
                            Linking.openURL(redirect_uri)
                        }
                    })
                } catch (error) {
                    console.log('Error: ', error.message)
                    onError()
                }
            }
        }

        getAuthCode()
        return () => {
            InAppBrowser.closeAuth()
        }
    }, [authCode, client_id, onError, redirect_uri, scopes])

    useEffect(() => {
        const getAuthRefreshToken = async () => {
            if (authCode) {
                try {
                    const { data }: { data: ApiDataResponse } = await axios.post(
                        'https://example.com/auth',
                        {
                            grant_type: 'authorization_code',
                            client_id: `${client_id}`,
                            code: `${authCode}`,
                            client_secret: `${client_secret}`,
                            redirect_uri: `${redirect_uri}`,
                        }
                    )

                    await Promise.all([
                        AsyncStorage.setItem('access_token', data.access_token),
                        AsyncStorage.setItem('refresh_token', data.refresh_token),
                    ])
                    setTimeout(() => {
                        onAuthComplete()
                    }, 1000)
                } catch (error) {
                    if (error.response) {
                        console.log('Error: ', error.response)
                    } else if (error.request) {
                        console.log('Error: ', error.request)
                    } else {
                        console.log('Error: ', error.message)
                    }
                    onError()
                }
            }
        }

        getAuthRefreshToken()
    }, [authCode, client_id, client_secret, onAuthComplete, onError, redirect_uri])

    return <LoadingIndicator />
}

How to increase Code Quality & testing as a Freelancer

I'm a self-thought dev and I started learning to code around 2 years ago. I'm already comfortable with documentations, many programming concepts. But I feel lacking in code quality & testing. When I look at some other projects it seems like their code is so simple with less lines, but does the same things that I do in more lines of code.

I'm mostly doing nodejs + reactjs. I took some software construction courses online, but they were mostly talk of concepts with very few examples of them. I'm also not working in a company so getting mentorship from a colleague is not an option.

How do you guys think that a freelancer can increase their code quality & testing?

Where can I learn the best coding practices?

Can you offer me any good open-source projects with high code quality and standards? or some books to dive into?

I appreciate every advice.

angular testing, conflicting component selectors

In an angular application unit test I would like to replace an imported component with a stub-component. I must import the module that defines the component because other components from it are required for the test. Simiar question: How to find which components are conflicting? How can I import all components from a module but some? Like a whitelist or blacklist of components.

TestBed.configureTestingModule({
  imports: [
    FormsModule, 
     /*Contains RichTextBoxComponent with selector 'app-rich-text-box'.
       How to import all components from this module but 'app-rich-text-box'.
     */
    UicompsModule],
  declarations: [ 
    ManageQuestionComponent, 
    /*Contains also a selector 'app-rich-text-box'*/
    StubRichTextBoxComponent],
  providers: [  ],
})
.compileComponents();