samedi 24 février 2018

How do I simulate a web request from an extranet? (C#)

I am working on tests that verify that our public-facing websites are operational. To do that, I have a piece of code I run to make an HttpWebRequest. How do I simulate being a user outside the intranet of the organization? Is there a way I can specify a user on the other side of the state? Would I add extra information to the header?

private async Task RunURLRequestAsync(string input)
    {
        string methodName = Utils.getCurrentMethod();
        Log("In:  " + methodName);
        try
        {
            var client = new HttpClient();
            var uri = new Uri(input);
            Log("URI is " + uri.ToString());
            HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(uri);
            webrequest.CookieContainer = new CookieContainer();
            webrequest.Method = "GET";
            webrequest.Timeout = 2000;
            HttpWebResponse response = (HttpWebResponse) webrequest.GetResponse();
            pageStatusCode = response.StatusCode.ToString();
            pageStatusDescription = response.StatusDescription.ToString();
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                pageStatusCode = "401 Unauthorized";
            }
            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream);
                string result = reader.ReadToEnd();
                Log("Web Page Contents: " + result);

            }
        }
        catch(Exception exc)
        {
            if(exc.Message.Contains("Unauthorized"))
            {
                pageStatusCode = "401";
                pageStatusDescription = "Unauthorized (Expected)";
                return;
            }
            else
            {
                Log(exc.Message);
                Log(exc.StackTrace);
            }
        }

     }

K8s mock service

I have a K8s service A that is dependent(calling it's APIs) on service B. I want to write a component test for service A only, how can I mock service B? which mean mock it's responses.

unit testing - how to check if a generic list has been created in C#

How do I check if a generic list has been created in a unit testing project, I am trying to do the Microsoft lab course and it is part of the exercise, there are many assert methods, which is the most suitable one to use to check if the list has been created?

Test On Espresso If A Dialog Fragment is Shown When a Button is Clicked

How do I make a test on Espresso where I could check whether a Dialog Fragment is shown when a Button is clicked?

I've been searching but never really found an answer.

Also could someone please guide me with TDD in Android. I've read alot but don't actually know how to start. I also dont understand the 70, 20, 10 rule. How do you know you are hitting them?

Also How do I know If I'm doing a Integration test over a Intrucmentation Test? I just really started studying these things and I'm frustrated and lost. Can please someone explain these things to me? :(

I really wanted to start developing with test in mind to improve my development cycle. Any help would be appreciated. Thanks in advance.

How detailed are GUI test cases in real projects?

Let's say I need to test a main page of a crm system. It has a menu and many elements on the page. My undestanding is prior to checking the functionality it's needed to test the GUI. Do I write a test case for each link/element to check their presence as per specification? A test case for each element to check that they are correctly aligned and responsive? Or is it enough to just say in one test case that everything is at its place and all the links work correctly?

React/Jest - mock fetch and wait for componentDidMount to re-render

I'm playing around with react and jest and I've came to the following situation where I simply cannot figure it out how should I do it.

Todo.js

import React from 'react';
import PropTypes from 'prop-types';
import TodoItem from './TodoItem';
import {fetchTodoItems} from '../helpers/todo';

class Todo extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            todos: [],
            error: false,
            loading: true
        };

        this.updateMockState = this.updateMockState.bind(this);
    }

    updateMockState() {
        this.setState({
            todos: [{ id: 8101, text: "Cook fresh food", status: "completed" }],
            loading: false
        });
    }

    componentDidMount() {
        // TODO: add error handling

        fetchTodoItems().then(response => {
            this.setState({
                todos: response.data,
                loading: false
            })
        }, error => {});
    }

    render() {
        let content;

        // TODO: add error handling

        if (this.state.loading) {
            return (
                <div>
                    <div>
                        <button id="update-data" onClick={this.updateMockState}>Update State</button>
                    </div>
                    <p>Todos are being fetched...</p>
                </div>
            );
        }

        return (
            content ||
            <div>
                <div>
                    <button id="update-data" onClick={this.updateMockState}>Update State</button>
                </div>
                <p><b>{this.state.todos.length}</b> todos fetched so far</p>
                {this.state.todos.map(
                    (todo) => <TodoItem key={todo.id} id={todo.id} status={todo.status} text={todo.text} />)}
            </div>
        );
    }
}

Todo.proptypes = {
    timeout: PropTypes.number
};

export default Todo;

Todo.test.js

import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import { mount, shallow, render } from 'enzyme';
import Todo from '../components/Todo';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import toJson from 'enzyme-to-json';

// TODO: remove sinon from NPM packages

Enzyme.configure({ adapter: new Adapter() });

const todos = { data: [{
    "id": 4404,
    "status": "active",
    "text": "Shopping List"
}, {
    "id": 7162,
    "status": "completed",
    "text": "Time Registration"
}]};

describe('Todo', () => {
    it('calls mock API', async () => {
        fetch = jest.fn().mockReturnValue(Promise.resolve(todos));
        const spy = jest.spyOn(Todo.prototype, 'componentDidMount');

        var component = mount(<Todo timeout={2000} />);
        component.instance().componentDidMount();
        expect(spy).toHaveBeenCalled();

        expect(toJson(component)).toMatchSnapshot();
    });
});

As you can see Todo component is a simple component that inside componentDidMount calls an API, get the response and displays. While waiting for the api call, some info is shown... There's also a button for dummy state update but that's not important for now.

fetchTodoItems (file is todo.js)

export const fetchTodoItems = () => {
    return fetch("data/todo.json").then(res => res.json());
};

My problem is the following:

  • I want to do a snapshot testing on Todo component as follows:
    1. First, right on render (before API call)
    2. Right after API call has finished with success

On 1st I'm supposed to see no todo items, but on 2nd I should see my todo items.

Here is TodoItem

import React from 'react';
import PropTypes from 'prop-types';

const TodoItem = (props) => {
    let htmlClass = [];
    if (props.status === 'completed') {
        htmlClass.push("todo-completed");
    }

    return (
        <ul>
            <p className={htmlClass.join(" ")}>
                <small>[#{props.id}]</small> {props.text} <i>({props.status})</i>
            </p>
        </ul>
    );
}

TodoItem.proptypes = {
    id: PropTypes.number.required,
    text: PropTypes.string.required,
    status: PropTypes.string.required
};

export default TodoItem;

So far I've tried the following:

  • pure snapshot testing with expect(component.toJSON()).toMatchSnapshot() - doesn't show results after API call

  • jest.spyON... the method is called but after that toMatchSnapshot still shows 1st snapshot with no data

  • return promise().then(... still no results

Any help?

EDIT:

If I remove API call from componentDidMount and use only setState, then snapshot testing shows todos items (without 1st case where it should say that todos are being fetched...) Why?? Shouldn't be the same?

If then only the promises are the root cause, how can I wait for all promises to finish?

Phpunit tests in laravel - make on null

I have several phpunit tests in my project. When fire them all in once - there is no problem - I got green. However, when I fire single test, like so phpunit --filter AuthTest tests/Feature/AuthTest.php. I get an error:

Error: Call to a member function make() on null
/Users/dummy/web/dummy/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:105