vendredi 1 juillet 2016

Mocking out angular.element in jasmine test

I have a controller that has a code snippet like this on controller initialization:

$scope.grid = angular.element('#MyGrid').kendoGrid(myData);

When I go to run jasmine tests, it dies before I can even get to my test code...the error I am getting is:

undefined is not a constructor (evaluating 'angular.element('#MyGrid').kendoGrid')

This makes sense because I obviously don't have the MyGrid element in the DOM. How can I mock out the angular.element call to return a mock object with the kendoGrid method?

Thanks!

Running JUnit TestSuite in command line [duplicate]

This question already has an answer here:

So I have been working on this program and I have written the whole thing in java, using Eclipse, and created a test suite for each of my classes.

When I try to run these test files using the normal command line commands, it gives me a whole bunch of errors.

Can someone please tell me how to run your JUnit test suite files using the command line?

iOS Unit Test target can't include host app's files that reference frameworks

Using XCode 7. Have an app that uses a 3rd party framework (old style xxx.framework, not post-iOS8 dynamic frameworks). Host app includes the framework files using the syntax

<MyExternalFrameworkNameHere/SomeFile.h>

and builds fine. I can #include using (quote-style) files from the host app that do not use any external frameworks in the unit test target .m file and the test target builds just fine. However when the test target references a file from the host app that itself includes a 3rd party framework the test target fails to build saying it can't find the header. Example:

Host app header named SomeHeader.h:

#include <UIKit/UIKit.h> // OK
#include <MyExternalFrameworkNameHere/SomeFile.h> // doesn't like this in test target

XCTest target AppTests.m:

#include "SomeHeader.h" //fails saying it cant find MyExternalFrameworkNameHere/SomeFile.h

If the test target directly includes the offending external framework file like this:

#include <SomeFile.h>

It works, but that doesn't help as I need to test the host app code that uses the framework, not the framework itself. What am I doing wrong here? I've tried adding the external framework to the test target's Link with binaries... but that didn't help.

Verify unit tests are actually being ran, not just skipped over because it's poorly written

We're using sinon and mocha to do our unit tests. I've come up with the problem several times where I write some tests (Maybe in a promise, or a callback, or a stub) and the tests in these do not ever get hit, thus they aren't actually testing anything.

I can't imagine being the only one who has done this, so was wondering what people do to verify the test they wrote is actually being ran.

As an example:

// sStuff...

let myStub = sinon.stub(className, "classMethod", (result) => {
    // THIS will never be ran.
    expect(result).to.be.equal(5);
});

expect(myStub.callCount).to.be.equal(0);

// Stuff...

The test won't complain it wasn't ran, because we have the callCount check, but in reality, we're never calling something on className to have the classMethod function to be called and testing the result against 5.

Any common solutions? I couldn't think of search terms for this.

Thanks!

sessionStorage is undefined in Jasmine

I followed this post to set my sessionStorage:

but no matter what I did, my sessionStorage is still undefined. I can step into storageMock(), but when I step out, it's still undefined. What did I do wrong?

Here's the code:

/// <reference path="../angular.js" />
/// <reference path="../angular-mocks.js" />
/// <reference path="../angular-animate.js" />
/// <reference path="../angular-ui/ui-bootstrap.js" />
/// <reference path="../angular-ui/ui-bootstrap-tpls.js" />

/// <reference path="../../../bluescopebuildings/app/app.js" />
/// <reference path="../../../bluescopebuildings/app/applicationapp.js" />


describe('Controller: applicationController', function () {
    // Storage Mock
    function storageMock() {
        var storage = {};

        return {
            setItem: function (key, value) {
                storage[key] = value || '';
            },
            getItem: function (key) {
                return storage[key] || null;
            },
            removeItem: function (key) {
                delete storage[key];
            },
            get length() {
                return Object.keys(storage).length;
            },
            key: function (i) {
                var keys = Object.keys(storage);
                return keys[i] || null;
            }
        };
    };
    var applicationCtrl, $scope, $window;


    beforeEach(function () {
        module('main');

        // INJECT! This part is critical
        // $rootScope - injected to create a new $scope instance.
        // $controller - injected to create an instance of our controller.
        // $q - injected so we can create promises for our mocks.
        // _$timeout_ - injected to we can flush unresolved promises.
        inject(function ($rootScope, $controller, $q, _$timeout_,_$window_) {
            $scope = $rootScope.$new();
            $timeout = _$timeout_;
            $window = _$window_;
            $window.sessionStorage = {};
            $window.sessionStorage = storageMock();
            $window.sessionStorage.setItem('userName', 'Thao');
            $window.sessionStorage.setItem('userID', 10);
            $window.sessionStorage.setItem('profileID', 25);

            applicationCtrl = $controller('applicationController', {
                $scope: $scope,
                $window: $window
            });
        });
    });

    it('should return profile', function () {
        //$scope.currentUserID = 10;
        //$scope.currentUserName = 'Thao';
        //$scope.currentJobID = 62;
        //$scope.profile = null;

        $scope.GetProfile();
        expect($scope.profile).not.toBe(null);
    });
});

I tried without calling storageMock(), but it still does not work. Thanks

Trying to inherit from unittest.TestCase and another class

I have a base class (which inherits only from object) with common tests for a set of sorting algorithms. Now, for each specific algorithm, I would like to create a test class which inherits both from unittest.TestCase and this class with common tests for all sorting algorithms.

For example, I would like to create a class to test, say, a bubble sort. Currently, I'm doing:

import unittest

from ands.algorithms.sorting import bubble_sort
from tests.algorithms.sorting.base_tests import *


class TestBubbleSort(unittest.TestCase, SortingAlgoTests):

    def __init__(self):
        unittest.TestCase.__init__(self)
        SortingAlgoTests.__init__(self, bubble_sort, True)


if __name__ == "__main__":
    unittest.main(verbosity=2)

Now, when I run TestBubbleSort using the command:

coverage run -m unittest discover . -v

I get a bunch of errors like:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/__main__.py", line 18, in <module>
    main(module=None)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/main.py", line 93, in __init__
    self.parseArgs(argv)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/main.py", line 117, in parseArgs
    self._do_discovery(argv[2:])
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/main.py", line 228, in _do_discovery
    self.test = loader.discover(self.start, self.pattern, self.top)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 341, in discover
    tests = list(self._find_tests(start_dir, pattern))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 398, in _find_tests
    full_path, pattern, namespace)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 452, in _find_test_path
    return self.loadTestsFromModule(module, pattern=pattern), False
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 123, in loadTestsFromModule
    tests.append(self.loadTestsFromTestCase(obj))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 92, in loadTestsFromTestCase
    loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/suite.py", line 24, in __init__
    self.addTests(tests)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/suite.py", line 57, in addTests
    for test in tests:
TypeError: __init__() takes 1 positional argument but 2 were given

Since I'm very new with this module unittest, but I had already created unit tests for a Java project, I'm not sure what's the problem.

I noticed that if I don't have the __init__ method, i.e., TestBubbleSort looks like this:

import unittest

from ands.algorithms.sorting import bubble_sort
from tests.algorithms.sorting.base_tests import *


class TestBubbleSort(unittest.TestCase, SortingAlgoTests):
    pass

if __name__ == "__main__":
    unittest.main(verbosity=2)

I don't have the errors above anymore. The problem is that I need to pass the sorting algorithm to the SortingAlgoTests base class, so I need to call its constructor, and usually I would do it in the __init__ method.

How can I solve this problem?

Robot Cleanner, solve with TDD and C#, complete solotion

I received the following question to solve with TDD but after I solved they told me it is not enough good. Please help me what is my mistake?

you can download my complete solution here

-----------------------Robot Cleanner---------------------------------------------------

Background:

When you have a lot of people working in an office it can get dirty quite quickly if you're not careful. However, cleaning staff are expensive. To save money on cleaning staff the best solution was deemed to be the creation of an automatic cleaning robot that cleans the office at night.

Assignment:

Your assignment is to build a prototype of this robot. The assignment is designed to be as simple as possible. The robot will, once given some instructions (shown below as input), run on its own without any human interference. In the morning we can ask the robot to report how many unique places in the office it has cleaned.

Input and Output Criteria:

• All input will be given on standard in.

• All output is expected on standard out.

• First input line: a single integer that represents the number of commands the robot should expect to execute before it knows it is done. The number will be in the range n (0 < n < 10, 000).

• Second input line: consists of two integer numbers that represents the starting coordinates x y of the robot. The value of each coordinate will be in the range x (-100, 000 < x < 100, 000) and y (-100, 000 y 100, 000).

• The third, and any subsequent line, will consist of two pieces of data. The first will be a single uppercase character c e {E, W, S, N), that represents the direction on the compass the robot should head. The second will be an integer representing the number of steps s (0 < s < 100,000) that the robot should take in said direction.

Special Notes :

• The robot will never be sent outside the bounds of the plane.

• All input should be considered well formed and syntactically correct. There is no need, therefore, to implement elaborate input parsing.

• Do not output any error messages. See previous point. The only output should be the number of unique places that the robot cleaned. See below.

• There will no leading or trailing white space on any line of input.

• There should be no leading or trailing whitespace on any line of output.

• Any multi-valued line of input will have a single white space character between each value.

• You can assume, for the sake of simplicity, that the office can be viewed as a grid where the robot moves only on the vertices.

• The robot cleans at every vertex it touches not just where it stops.

The Output :

The output of your program should be a number u, which represents the number of unique places in the office that were cleaned. The output of the number u should be prefixed by "=> Cleaned:" (excluding the quotes).

Example input:

2

10 22

E 2

N 1

Example output: => Cleaned: 4

---------------------------My Answer---------------------------------------------

Program.cs

using System;
using ClassLibraryRobotCleaner;

namespace ConsoleApplicationRobotCleaner
{
    class Program
    {
        static void Main(string[] args)
        {
            RobotCleaner robot = new RobotCleaner();
            robot.NumberOfCommands=Convert.ToInt32(Console.ReadLine());

            string[] coordinate = Console.ReadLine().Split(' ');
            robot.StartingCoordinates=new Coordinate( Convert.ToInt32(coordinate[0]), Convert.ToInt32(coordinate[1]));


            if (robot.NumberOfCommands > 0)
            {
                for (int i = 1; i <= robot.NumberOfCommands; i++)
                {
                    string[] vector = Console.ReadLine().Split(' ');
                    robot.AddVector(new Vector(Convert.ToChar(vector[0]), Convert.ToInt32(vector[1])));
                }
            }

            robot.StartSession();


            Console.WriteLine("=> Cleaned: " + robot.GetNumberOfCleanedPlaces());

            Console.ReadKey();


        }
    }
}

Test Class using ClassLibraryRobotCleaner; using NUnit.Framework;

namespace NUnit.TestsRobotCleaner
{
    [TestFixture]
    public class TestClassRobotCleaner
    {
        [Test]
        public void NumberOfCommands()
        {
            RobotCleaner crc = new RobotCleaner();
            crc.NumberOfCommands = 2;

            Assert.AreEqual(crc.NumberOfCommands, 2);
        }


        [Test]
        public void StartingCoordinates()
        {
            RobotCleaner crc = new RobotCleaner();
            Coordinate cc = new Coordinate(2, 3);
            crc.StartingCoordinates = cc;

            Assert.AreEqual(cc.X, 2);
            Assert.AreEqual(cc.Y, 3);
        }

        [Test]
        public void AddVectors()
        {
            RobotCleaner crc = new RobotCleaner();
            crc.AddVector(new Vector('E', 5));
            crc.AddVector(new Vector('S', 3));

            Assert.AreEqual(crc.GetNumberOfVectors(), 2);
        }

        [Test]
        public void GetOneVector()
        {
            RobotCleaner crc = new RobotCleaner();
            crc.AddVector(new Vector('E', 5));
            crc.AddVector(new Vector('S', 3));
            crc.AddVector(new Vector('W', 2));

            Assert.AreEqual(crc.GetOneVector(0).Directon, 'E');
            Assert.AreEqual(crc.GetOneVector(0).Steps, 5);

            Assert.AreEqual(crc.GetOneVector(1).Directon, 'S');
            Assert.AreEqual(crc.GetOneVector(1).Steps, 3);

            Assert.AreEqual(crc.GetOneVector(2).Directon, 'W');
            Assert.AreEqual(crc.GetOneVector(2).Steps, 2);

        }



        [Test]
        public void GetCurrentCoordinate()
        {
            RobotCleaner crc = new RobotCleaner();
            crc.NumberOfCommands = 0;
            crc.StartingCoordinates = new Coordinate(5, 4);
            crc.StartSession();

            Assert.AreEqual(crc.GetCurrentCoordinate().X, 5);
            Assert.AreEqual(crc.GetCurrentCoordinate().Y, 4);
        }


        [Test]
        public void GetNumberOfCleanedPlaces()
        {
            RobotCleaner crc = new RobotCleaner();
            crc.NumberOfCommands = 0;
            crc.StartingCoordinates = new Coordinate(5, 4);
            crc.StartSession();

            Assert.AreEqual(crc.GetNumberOfCleanedPlaces(), 1);
        }


        [Test]
        public void GetCurrentCoordinate_WithOneCommand()
        {
            RobotCleaner crc = new RobotCleaner();
            crc.NumberOfCommands = 1;
            crc.StartingCoordinates = new Coordinate(0, 0);
            crc.AddVector(new Vector('E', 1));
            crc.StartSession();

            Assert.AreEqual(crc.GetCurrentCoordinate().X, 1);
            Assert.AreEqual(crc.GetCurrentCoordinate().Y, 0);
        }

        [Test]
        public void GetCurrentCoordinate_WithTwoCommand()
        {
            RobotCleaner crc = new RobotCleaner();
            crc.NumberOfCommands = 2;
            crc.StartingCoordinates = new Coordinate(0, 0);
            crc.AddVector(new Vector('E', 1));
            crc.AddVector(new Vector('N', 2));
            crc.StartSession();

            Assert.AreEqual(crc.GetCurrentCoordinate().X, 1);
            Assert.AreEqual(crc.GetCurrentCoordinate().Y, 2);
        }

        [Test]
        public void GetNumberOfCleanedPlaces_withTwoCommands()
        {
            RobotCleaner crc = new RobotCleaner();
            crc.NumberOfCommands = 2;
            crc.StartingCoordinates = new Coordinate(5, 4);
            crc.AddVector(new Vector('E', 5));
            crc.AddVector(new Vector('N', 6));
            crc.StartSession();

            Assert.AreEqual(crc.GetNumberOfCleanedPlaces(), 12);
        }

        [Test]
        public void GetNumberOfCleanedPlaces_withTwoCommandsOverlap()
        {
            RobotCleaner crc = new RobotCleaner();
            crc.NumberOfCommands = 2;
            crc.StartingCoordinates = new Coordinate(5, 4);
            crc.AddVector(new Vector('E', 5));
            crc.AddVector(new Vector('W', 6));
            crc.StartSession();

            Assert.AreEqual(crc.GetNumberOfCleanedPlaces(), 7);
        }

    }

}

Robot Class

using System;
using System.Collections.Generic;

namespace ClassLibraryRobotCleaner
{
    public class RobotCleaner
    {
        public int NumberOfCommands { get; set; }
        public Coordinate StartingCoordinates { get; set; }

        private Coordinate _currentCoordinates;
        private List<Vector> _vectorsList = new List<Vector>();
        private List<Coordinate> _cleanedCoordinates = new List<Coordinate>();


        public void AddVector(Vector vector)
        {
            _vectorsList.Add(vector);
        }

        public int GetNumberOfVectors()
        {
            return _vectorsList.Count;
        }

        public Vector GetOneVector(int v)
        {
            return _vectorsList[v];
        }
        public Coordinate GetCurrentCoordinate()
        {
            return _currentCoordinates;
        }

        public int GetNumberOfCleanedPlaces()
        {
            return _cleanedCoordinates.Count;
        }
        public void StartSession()
        {

            GoToTheCoordinate(StartingCoordinates);
            DoCleaningCurrentPosition();

            for (int i = 0; i < NumberOfCommands; i++)
            {
                Vector v = _vectorsList[i];
                for (int j = 0; j < v.Steps; j++)
                {
                    GoToTheCoordinate(Vector.ConvertDirectionToCoordinate(v.Directon) + _currentCoordinates);
                    DoCleaningCurrentPosition();
                }
            }
        }

        private void DoCleaningCurrentPosition()
        {
            Coordinate ccc = _currentCoordinates;
            if (_cleanedCoordinates.Exists(l => l.X == ccc.X && l.Y == ccc.Y) == false)
            {
                //Robot Cleaning Right Now
                _cleanedCoordinates.Add(ccc);
            }
        }

        private void GoToTheCoordinate(Coordinate coordinate)
        {
            _currentCoordinates = coordinate;
        }

    }
}