mercredi 31 mai 2017

Compile specific rust tests into binary

I would like to compile a binary which runs a certain subset of tests. When I run the following, it works:

ubuntu@ubuntu-xenial:/ox$ cargo test hash::vec
    Finished dev [unoptimized + debuginfo] target(s) in 0.11 secs
     Running target/debug/deps/ox-824a031ff1732165

running 9 tests
test hash::vec::test_hash_entry::test_get_offset_tombstone ... ok
test hash::vec::test_hash_entry::test_get_offset_value ... ok
test hash::vec::test_hash_table::test_delete ... ok
test hash::vec::test_hash_table::test_delete_and_set ... ok
test hash::vec::test_hash_table::test_get_from_hash ... ok
test hash::vec::test_hash_table::test_get_non_existant_from_hash ... ok
test hash::vec::test_hash_table::test_override ... ok
test hash::vec::test_hash_table::test_grow_hash ... ok
test hash::vec::test_hash_table::test_set_after_filled_with_tombstones ... ok

test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 8 filtered out

However, when I try to run target/debug/deps/ox-824a031ff1732165, it runs all my tests, not just the 9 specified in hash::vec.

I've tried to run cargo rustc --test hash::vec but I get error: no test target namedhash::vec.cargo rustc -- --testworks, but creates a binary that runs all tests. If I trycargo rustc -- --test hash::vec`, I get:

   Compiling ox v0.1.0 (file:///ox)
error: multiple input filenames provided

error: Could not compile `ox`.

cargo rustc -h says that you can pass NAME with the --test flag (--test NAME Build only the specified test target). So, I'm wondering what "NAME" is and how to pass it in so I get a binary that only runs the specified 9 tests in hash::vec. Any help would be appreciated!

How to test an angular service function nested promises?

Heres what my service kind of looks like

TestService.initializeDefaults = function() {
        var qPromise = $q.defer();
        $q.all({localResource : localResource.fetch(),
                item : itemResource.fetch()}).then(function(directories){

            //stuff happens with directories
            $q.all({
                thing1 : anotherThingFetch.fetch(),
                thing2: someThingFetch.fetch(),
                thing3: thingFetch.fetch()
            }).then(function(funData) {
                //stuff happens with the data

                preventiveServicesService.fetch().then(function() {

                    //stuff happens
                });

            });
        }.bind(this));
        return qPromise;
    };

And Im attempting to use karma to test that all the functions within this initializeDefaults method have run. Meaning that essentially all the fetch's happened. Heres what I have that works in the test so far:

it("should initialize defaults (Scenario 1)", function() {

            service.initializeDefaults();

            rootScope.$apply();

            expect(localResourceMock.fetch).toHaveBeenCalledWith();
            expect(itemResourceMock.fetch).toHaveBeenCalledWith();

Protractor Not Connecting To Localhost:8080 in Angular 2 App Testing - ERR_CONNECTION_REFUSED

I am trying to run my protractor tests but am having some problems connecting to the url I am requesting in my browser.get function call.

protractor.conf.js:

const { SpecReporter } = require('jasmine-spec-reporter');


exports.config = {
      framework: 'jasmine',
      allScriptsTimeout: 11000,
      specs: ['./e2e_tests/components/**/*.spec.ts'],
      capabilities: {
          'browserName': 'chrome'
      },
      directConnect: true,
      jasmineNodeOpts: {
          showColors: true,
          defaultTimeoutInterval: 30000,
          print: function() {}
      },
      beforeLaunch: function() {
         require('ts-node').register({
            project: 'e2e_tests/tsconfig.e2e.json'
        });
      },
      onPrepare() {
           jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
         }
 };

spec.ts

 import { browser, element, by } from 'protractor';

 describe('Header Bar Component', function () {
   beforeEach(function () {
        browser.get('http://localhost:8080/#/dashboard');
   });

  it('should have a title', function () {
       var headerElement = element(by.tagName('h2'));
       expect(headerElement.getText()).toMatch('Galileo Example');
  });

  it('should have a menu', function () {
      var menu = element(by.tagName('md-menu'));
      expect(menu).not.toBeFalsy();
 });

 it('should have a settings option', function () {
      var menuOption = element(by.buttonText('Settings'));
      expect(menuOption).not.toBeFalsy();
  });
});

I have tried cleaning my browsing history / cache and also restarting my DNS Client in services.msc. Both did not provide a solution.

The "View Site Information" tab in the browser url is saying "Not Secure" when Protractor is trying to load the browser but in the end it says: ERR_CONNECTION_REFUSED

Does anyone know what I'm missing here? Thanks

Magento Test Area for not loosing customers data

I need to publish a ready magento ecommerce. But I want to make sono customization in the future. I would like to use a Test area to make all the customization that I want, and then update the official site. My doubt is, if I create a site/Test folder, and copy the DB from the official site, in this moment I lose all the future subscription and order from the DB copy. So when after some days, I ended my customization, new users have subscribed and new order have been placed. So if I import back the DB copied few days before, I lose those. How I need to proceed to avoid this problem and don't lose anything from customers and orders?

Mocking Redis Constructor with Sinon

I'm trying to figure out a way to mock redis in this module:

//module.js

const Redis  = require('ioredis');
const myFunction = {
  exists: (thingToCheck) {
    let redis_client = new Redis(
      6379,
      process.env.REDIS_URL,
      {
        connectTimeout: 75,
        dropBufferSupport: true,
        retryStrategy: functionHere
      });

    redis_client.exists(thingToCheck, function (err, resp) {
      // handlings in here
    });
  }
};



// test-module.js

const LambdaTester = require('lambda-tester');
const chai = require('chai');
const expect = chai.expect;
const sinon = require('sinon');
const mockRedis = sinon.mock(require('ioredis'));


describe( 'A Redis Connection error', function() {



  before(() => {

    mockRedis.expects('constructor').returns({
      exists: (sha, callback) => {
        callback('error!', null);
      }
    });

  });
  it( 'It returns a database error', function() {


    return LambdaTester(lambdaToTest)
      .event(thingToCheck)
        .expectError((err) => {
          expect(err.message).to.equal('Database error');
        });
  });
});

I also tried a few variations, but I'm kind of stuck as I basically need to mock the constructor and I'm not sure Sinon supports this?

mockRedis.expects('exists').returns(
  (thing, callback) => {
    callback('error!', null);
  }
);
sinon.stub(mockRedis, 'constructor').callsFake(() => console.log('test!'));
sinon.stub(mockRedis, 'exists').callsFake(() => console.log('test!'));

Not sure what else to try here, I also tried using rewire as suggested here, but using mockRedis.__set__("exists", myMock); never set that private variable.

I want to fake my error paths ultimately.
I would love to hear what others are doing to test redis in node js 😄.

Testing arguments of the method tested

is it possible or good idea to test arguments of the class that has the method mocked ? Example :

class CarType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder->addEventSubscriber(new User('argument example')

    }
}

This is my test:

    public function testFormBuilder()
    {

    $builder = $this->getMockBuilder('Symfony\Component\Form\FormBuilder')
        ->disableOriginalConstructor()
        ->getMock();

       // Test    
        $type = new CarType();

            $this->builder->expects($this->once())
                ->method('addEventSubscriber')
                ->with(
                    $this->isInstanceOf(User::class)
                );

            $type->buildForm($this->builder, []);


    }

This test work fine, But... I want to know if the first argument of the User class is a string, but can I do in this same test?

How do I tell if the redirect on my site is due to a Google Optimize test?

On my site right now, I have an alert that appears before the user leaves the site asking them if they're sure they want to leave.

This is interfering with a Google Optimize test I'm running because the test is redirecting traffic from my main page to two variant pages and causing the alert to appear as soon as the person hits the page.

I was wondering if anyone knows if there's an event fired with these Google redirect tests or if there's a way to tell when a redirect is happening or who it's coming from, so I can properly handle it.

ChromeDriver doesn't click on element. Selenium. Java

I am making scenario to automatizate some actions on this site https://csgo500.com/

Code of my class:

package scenario;

import managers.loaders.CheckBy;
import driver.sleep.DriverSleeper;
import exceptions.NotNowException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;


public class CSGO500Scen implements SiteScenarioInt{
    private WebDriver driver;

    public CSGO500Scen(WebDriver driver){
        this.driver = driver;
    }

    public void gamble() throws NotNowException {
        driver.get("https://csgo500.com/");

        CheckBy.id("gotit-btn");
        driver.findElement(By.id("gotit-btn")).click(); //accept terms of use
        DriverSleeper.sleep(3);

        CheckBy.id("content-login");
        DriverSleeper.sleep(3);
        driver.findElement(By.xpath("//*[@id=\"content-login\"]")).click(); //HERE IS A PROBLEM

        CheckBy.className("btn_green_white_innerfade");
        driver.findElement(By.className("btn_green_white_innerfade")).click(); //login with steam

        CheckBy.className("nav-rewards");
        driver.findElement(By.className("nav-rewards")).click();

        if(!isActive()){
            throw new NotNowException("CSGO500.com");
        }
        else{
            while(true){
                DriverSleeper.sleep(3);
                if (!isActive()){
                    break;
                }
            }
        }
    }

    private boolean isActive(){
        if (driver.findElement(By.id("reward-claim-submit-disabled")).getAttribute("style").equals("display: none;")){
            return true;
        }
        else{
            return false;
        }
    }
}

First step is to Accept Use Terms. Ok, it's done, but when i want to click on "Login" button, i get following error(Login button id is "content-login") :

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Element <a id="content-login" href="http://ift.tt/2royEJ8" data-lang="login" class="" data-__original="
...
" data-__trid="1000018" data-__translated="en">Login</a> is not clickable at point (946, 33). Other element would receive the click: <div id="login-content">...</div>

It writes that this page contains one more element with the same id. I have written Test to get number of elements with this id:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.concurrent.TimeUnit;
public class test {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\user\\IdeaProjects\\sitescen\\src\\main\\resources\\chromedriver.exe" );
        WebDriver driver = new ChromeDriver();
        driver.get("http://ift.tt/1UtLAUt");
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        System.out.print(driver.findElements(By.xpath("//*[@id=\"content-login\"]")).size());

    }
}

I got output:

1

So, i have only one element with the same id, and no elements arround this button.

To prevent errors of loading, i use sleep of my DriverSleeper class which accept number of seconds to sleep.

Finally, i don't know, how to click this button, and hope, that you help me.

Fakes dll files are not copied to Target Directory

I am building Visual Studio project. I have added fakes files for few dlls referenced by this project. Fakes assemblies are generated and added to directory named "FakesAssemblies". In my company there is a requirement that in csproj file for project we cannot have HintPath for References. So references to fakes look like this in csproj files:

<Reference Include="Project.Basic.Fakes" />

Project.Basic is part of Solution. Fake dlls should be copied from FakesAssemblies to output directory: {Solution_path}\bin\Debug (Debug or Release at the end). But only some fakes assemblies are copied to such directory (after I run 'Rebuild' on Project.Basic). What should I do to copy all fakes assemblies to output directory? I am using Visual Studio 2013 Update 5.

How to include Exceptions and Errors in log4j

I have made log4j appender that stores all logs into one file:

log.info("Hello world");

will store Hello World into the file. How I can make that even Exceptions are stored into that file as log. For example statement:

log.info(5 / 0);

should store whole stack from DivisionByZero Exception into file that is stated in log4j appender.

P.S. I know that I can put log.info(e.printStackTrace()) into catch clause, but I want every catched and non-catched exception is logged.

P.S.S. I know I can redirect stderr output to file, but I don't want touch the console.

How testing mobile app on remote country

Hi I'm working on an mobile app android/ios and it need access to mobile network, but the real customer is on other country. How can we testing that app remotly?

how to match a mocked call with wildcard in scala test?

looking for something like this:

    //Mockito when rawData.filter(filter) thenReturn mockInfo
    //but I want
    Mockito when rawDataRDD.filter(*) thenReturn mockInfo

should be related with

m expects 'forward withArgs (*) once

but seems my scala doesn't support ' symbol yet. so how shall I match a spied call with wildcard in scala test ?

Fitnesse execute too many tests

I just wrote my first fitnesse test. This test is executed with the help of fitnesse runner. My project contains 1 fitnesse test. This test itself succeeds, but when start the test fitnesse seemse to execute the test twice. The second test fails.

Failed tests:
fitnesse.RunLoginFT at least one test executed in LoginTest
0 right, 0 wrong, 0 ignored, 0 exceptions

Tests run: 2, Failures: 1, Errors: 0, Skipped: 0

I ran the next test:

@RunWith(FitNesseRunner.class)
@FitNesseRunner.Suite("LoginTest")
@FitNesseRunner.FitnesseDir("./src/test/resources")
@FitNesseRunner.OutputDir("target/fitnesse")
public class RunLoginFT {

}

Any idea what goes wrong?

Test is not failing even though assertion has failed

I have the same issue to one stated in this question, but I would cover it with a code sample that someone can answer it.

The thing is that I have 2 classes. One of them contains @Test method which calls validation where all asserts are put. The problem arises when that validation method is called via reflection, like this:

public class TestClass {
    @Test
    public void test() {
      ValidationClass validationClass = new ValidationClass();
      validationClass.getClass().getDeclaredMethod("validate").invoke(validationClass, null);
    }
}

public class ValidationClass {
    public void validate() {
        Assert.fail("some message");
    }
}

In this case, the overall test will pass even though assertion failed in validation method. How to fix it? In case I am not using reflection:

@Test
public void test() {
  ValidationClass validationClass = new ValidationClass();
  validationClass.validate();    // NOT USING REFLECTION
}

it will work, but that's not what I want.

laravel/codeception : test if json response contains only certain keys

I have a json array coming from my api as response:

{
  "data": [
    {
      "id": 1,
      "name": "abc"
    }
}

I am using laravel for api and laravel-codeception for testing.

public function getAll(ApiTester $I)
    {
        $I->sendGET($this->endpoint);
    }

I have to test if the response contains only id and name key (not any other key) example this response should fail the test.

{
      "data": [
        {
          "id": 1,
          "name": "abc",
          "email":"abc@xyz"
        }
    }

I have found $I->seeResponseContainsJson(), but it checks if JSON is present or not. It does not check if JSON response contains only specified keys.

Thanks.

Can Any body Suggest what is the best open source test management tool?

Presently we are not using any test management tool. We will start using If there are any free test management tools. I have seen below are the free tools.http://ift.tt/2jVkr3v.

Suggest me any of the best. Thanks in advance.

How to get the *-tests.jar for configuring Appium with AWS device farm?

i was created a maven project in eclipse.A sample code i tried is Working fine in my physical device.For uploading my test cases to AWs console need this *-tests.jar file. But this file is not creating in my project

Project Structure is given below

My project hierarcy is given below

Source code i tried is also attached below

Base class

 package ********;

import io.appium.java_client.android.AndroidDriver;    
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;


import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

public class ************* {
     protected AndroidDriver driver;
        protected WebDriverWait wait;

        //before Test Annotation makes a java function to run every time before a TestNG test case
        @BeforeTest
        protected void createAppiumDriver() throws MalformedURLException, InterruptedException {

              DesiredCapabilities capabilities = new DesiredCapabilities();
              capabilities.setCapability("deviceName", "0123456789ABCDEF");
              capabilities.setCapability(CapabilityType.BROWSER_NAME, "Android");
              capabilities.setCapability(CapabilityType.VERSION, "5.0");
              capabilities.setCapability("platformName", "Android");
              capabilities.setCapability("appPackage", "**********);
              capabilities.setCapability("appActivity", "********");
              capabilities.setCapability("unicodekeyboard", true);
              capabilities.setCapability("resetkeyboard", true);
              driver = new AndroidDriver(new URL("http://ift.tt/1eWSHgW"), capabilities);          
              driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
              WebDriverWait wait = new WebDriverWait(driver, 300);
              wait.until(ExpectedConditions.elementToBeClickable(By.className("android.widget.FrameLayout")));
        }

        //After Test Annotation makes a java function to run every time after a TestNG test case
        @AfterTest
        public void afterTest(){

        //quit the driver
        driver.quit();
        }

    }

Screen class

     package **********;

        import io.appium.java_client.MobileBy;

        import org.openqa.selenium.By;
        import org.openqa.selenium.support.ui.ExpectedConditions;
        import org.testng.annotations.Test;


        public class QuickPay extends ************ {
            /*--------------------------------Enter pin Starts---------------------------------*/

             //Enter 4 digit pin to login
             @Test
             public void T4a_Login() {      
                driver.findElement(By.xpath("//android.view.View[contains(@resource-id,'ext-button-1')]")).sendKeys("1234");
             } 


        /*--------------------------------Enter pin Ends---------------------------------*/


        /*QuickPay Starts*/

        /*--------------------------------Quick pay to Federal Bank Account starts---------------------------------*/

             //Click on quick pay
             @Test
             public void T5a_QuickpayF() {      
                driver.findElement(By.xpath("//android.view.View[contains(@resource-id,'ext-button-30')]")).click();    
             } 

             //Enter account number , Amount and click quick pay
             @Test
             public void T5b_QuickpayF() {      
                driver.findElement(By.xpath("//android.widget.EditText[contains(@resource-id,'ext-element-229')]")).sendKeys("10015000301404"); 
                driver.findElement(By.xpath("//android.widget.EditText[contains(@resource-id,'ext-element-236')]")).sendKeys("50"); 
                driver.hideKeyboard();  
                driver.findElement(By.xpath("//android.view.View[contains(@resource-id,'ext-button-34')]")).click();
             }

             //Click on confirm button
             @Test
             public void T5c_QuickpayF() {      
                 driver.findElement(By.xpath("//android.view.View[contains(@resource-id,'ext-button-38') and @index='0']")).click();
             }

             //Enter pin for Quick paya-Federal bank
             @Test
             public void T5d_QuickpayF() {      
                 driver.findElement(By.xpath("//android.view.View[contains(@resource-id,'ext-button-45') and @index='1']")).click();    
                 driver.findElement(By.xpath("//android.view.View[contains(@resource-id,'ext-button-46') and @index='2']")).click();
                 driver.findElement(By.xpath("//android.view.View[contains(@resource-id,'ext-button-47') and @index='3']")).click();
                 driver.findElement(By.xpath("//android.view.View[contains(@resource-id,'ext-button-48') and @index='4']")).click();
             }

             //Click on home for redirect to Home page
             @Test
             public void T5e_QuickpayF() {  
                 System.out.println("testtt");  
                 driver.findElement(By.xpath("//android.view.View[contains(@resource-id,'ext-button-60')and @index='0']")).click();
                 System.out.println("rt");
             }



        /*--------------------------------Quick pay to Federal Bank Account Ends---------------------------------*/

        }

**PoM.xml**

<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU" xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.aws.appium</groupId>
  <artifactId>appium-android-test</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

 <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-jar-plugin</artifactId>
             <version>2.6</version>
             <executions>
                <execution>
                     <goals>
                        <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-jar-plugin</artifactId>
             <version>2.6</version>
            <executions>
                 <execution>
                     <goals>
                         <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
 </build>
   <properties>
        <appium.version>3.3.0</appium.version>
        <testng.version>6.9.10</testng.version>
    </properties>

    <dependencies>

        <!-- Appium -->
        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>${appium.version}</version>
        </dependency>

        <!-- testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

it is deleted amk

if you downvote my question.. please say why you downvote...

mardi 30 mai 2017

angularjs unit test,test service 'Expected undefined to be 5, 'should have expected no. of strategys'.'

I follow the official website of the process to write an isolated service test, but there is a problem, I guess the data is not recognized, I am a novice, I do not know what this is caused by this.

test service get should have expected fake strategys (then) FAILED

//strategyTables.service.ts
@Injectable()
@BaseUrl("http://localhost:8080/api/")
@DefaultHeaders({
  'Accept': 'application/json',
  'Content-Type': 'application/json'
})

export class StrategyTablesService extends RESTClient {

  public constructor(http: Http) {
    super(http);
  }

  protected requestInterceptor(req: Request) {

  }

  protected responseInterceptor(res: Observable<Response>): Observable<Response> {
    return res;
  }

  @GET("strategys/")
  public getStrategys( @Query("sort") sort?: string ): Observable<any> { return null; };


  // 分页条件查询
  @GET("controller/getstrategys/strategyname={strategyname}&isuseragent={isuseragent}&iscookie={iscookie}&&size={size}&page={page}&sorts={sorts}")
  public getAllstrategys( @Path('strategyname') strategyname:string ,@Path('isuseragent') isuseragent:string ,@Path('iscookie') iscookie:string ,@Path('page') page:number,
                           @Path('size') size:number, @Path('sorts') sorts:string): Observable<any> { return null; };
  @GET("strategys/{id}")
  public getStrategyById( @Path("id") id: string ): Observable<any> { return null; };

  @PUT("strategys/{id}")
  public updateStrategyById( @Path("id") id: number, @Body strategy: Strategy): Observable<any> { return null; };

  @DELETE("strategys/{id}")
  public deleteStrategyById( @Path("id") id: number): Observable<any> { return null; };

  @POST("controller/savestrategy")
  public createStrategy(@Body strategy: Strategy): Observable<any> { return null; };

}
//strategyTables.service.spec.ts
import {StrategyTablesService} from "./strategyTables.service";
import {Http, HttpModule, XHRBackend,Response, ResponseOptions} from "@angular/http";
import {TestBed, inject, async} from "@angular/core/testing";
import {MockBackend,MockConnection} from"@angular/http/testing";
import {Strategy} from "../domain/strategy";

import 'rxjs/add/observable/of';

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/toPromise';

const makeStrategyData = () => [
  {
    "id": 20,
    "strategyname": "abcee",
    "isuseragent": "?",
    "depth": 10,
    "download_delay": 3,
    "iscookie": "?",
    "agent": "2",
    "starttime": "2017?4?3? 20:7:28"
  },
  {
    "id": 19,
    "strategyname": "efg",
    "isuseragent": "?",
    "depth": 10,
    "downloadDelay": 3,
    "iscookie": "?",
    "agent": "2",
    "starttime": "2017?4?3? 20:5:39"
  },
  {
    "id": 18,
    "strategyname": "abcde",
    "isuseragent": "?",
    "depth": 10,
    "download_delay": 3,
    "iscookie": "?",
    "agent": "2",
    "starttime": "2017?4?3? 20:0:17"
  },
  {
    "id": 16,
    "strategyname": "11",
    "isuseragent": "?",
    "depth": 2,
    "download_delay": 3,
    "iscookie": "?",
    "agent": "2",
    "starttime": "2017?4?3? 19:48:21"
  },
  {
    "id": 14,
    "strategyname": "abc",
    "isuseragent": "?",
    "depth": 2,
    "download_delay": 3,
    "iscookie": "?",
    "agent": "2",
    "starttime": "2017?4?3? 19:48:4"
  }
] as Strategy[];

describe('test service',()=> {
  beforeEach(()=>{
    TestBed.configureTestingModule({
      imports:[HttpModule],
      providers:[
        StrategyTablesService,
        { provide: XHRBackend, useClass: MockBackend }
      ]
    });
  });

  it('can instantiate service when inject service ',inject([StrategyTablesService],(service:StrategyTablesService) =>{
    expect(service instanceof StrategyTablesService).toBe(true);
  }));

  it('can instantiate service with "new"', inject([Http], (http: Http) => {
    expect(http).not.toBeNull('http should be provided');
    let service = new StrategyTablesService(http);
    expect(service instanceof StrategyTablesService).toBe(true, 'new service should be ok');
  }));

  it('can provide the mockBackend as XHRBackend',
    inject([XHRBackend], (backend: MockBackend) => {
      expect(backend).not.toBeNull('backend should be provided');
    }));

  describe('get',()=> {
    let backend: MockBackend;
    let service: StrategyTablesService;
    let fakeStrategy: Strategy[];
    let response: Response;

    beforeEach(inject([Http, XHRBackend], (http: Http, be: MockBackend) => {
      backend = be;
      service = new StrategyTablesService(http);
      fakeStrategy = makeStrategyData();
      let options = new ResponseOptions({status: 200, body: {data: fakeStrategy}});
      response = new Response(options);
    }));

   it('should have expected fake strategys (then)', async(inject([], () => {
      backend.connections.subscribe((c: MockConnection) => c.mockRespond(response));

      service.getAllstrategys("","","",0,5,"id").toPromise()
      // .then(() => Promise.reject('deliberate'))
        .then(strategys => {
          expect(strategys.length).toBe(fakeStrategy.length,
            'should have expected no. of strategys');
        });
    })));
  });
});  

Expected undefined to be 5, 'should have expected no. of strategys'.

Reggression and tests needed

Let's assume that we have to examine house prices and we have 5 variables.... PRICE,SIZE ,AGE, MANHATTAN(MANHATTAN= if it is located in Manhattan) and TAX. And i have 3 questions : 1. how can we generate a model that calculates the PRICE of a house according to the other variables. 2.HOW can we tell if it is statistically important if house is located in MANHATTAN? 3. WHICH are the tests needed to be done in an example like that to be valid? ( normality?residuals homo etc) Of course i need the answer in R programming

data corrupted after train_test_split

I am using the sklearn train_test_split() method to create my training and test data set. Therefore, I use the following straight forward code:

from sklearn.cross_validation import train_test_split
print(y[0])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(y_train[0])

However, y before the split contains values like this:

[ 0.01689708  0.06298003  0.04147466  0.00460829  0.03686636  0.
  0.02457757  0.01996928  0.0015361   0.01689708  0.01536098  0.0015361
  0.02304148  0.02150538  0.01382488  0.03686636  0.0015361   0.01228879
  0.00460829  0.0015361   0.093702    0.00460829  0.00614439  0.00614439
  0.0030722   0.06605223  0.          0.00768049  0.          0.0030722
  0.0030722   0.0015361   0.0015361   0.0015361   0.0030722   0.0015361
  0.0030722   0.00614439  0.01382488  0.          0.          0.0030722
  0.0015361   0.02150538  0.01228879  0.00921659  0.01382488  0.00460829
  0.0030722   0.0030722   0.0030722   0.0030722   0.01843318  0.00768049
  0.          0.01075269  0.03072197  0.0015361   0.00460829  0.00460829
  0.00614439  0.00614439  0.0030722   0.          0.01075269  0.0030722
  0.0015361   0.02611367  0.0015361   0.          0.          0.0030722   0.
  0.          0.          0.0030722   0.0030722   0.          0.00460829
  0.0015361   0.01996928  0.00460829  0.0030722   0.0030722   0.01382488
  0.0030722   0.01536098  0.00768049  0.00460829  0.02918587  0.          0.0015361
  0.02304148  0.0030722   0.00768049  0.00768049  0.          0.0030722
  0.03225806  0.0030722 ]

While the print after the split yields only 0's:

[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

Of course, the 0 index does not correspond to the same datapoint after splitting. But the y data before the split, does not contain any 0's.

Handle same Python exception for all tests in test class

Similar to a setUp() method, is there a way to define in one place how a certain exception is handled for all the tests in a given TestCase test class?

My use-case: the stack trace of mock/patch's assert_any_call only gives the expected call it could not find, but I want to add the actual calls against the mock. Each unit test can add this info to the stack trace in an except clause, but I want it defined in one place to avoid bloated code.

Unit testing a PHP file with no method defined

I have a PHP file that will only connect to DB and displays the resultset in an HTML table. How do we create a unit test script for such PHP file? Thanks a lot in advance.

How to white-box test a Java code snippet?

How would this code be white-box tested? This is a loop test perhaps. Click for Code Image HERE

Are there any programs\framework's for automatic testing of mobile games made on the engine "Unity"?

Faced the problem of automatic testing of my company's project on mobile devices. The fact is that we are doing the project on the engine "Unity" and then doing a build for the IOS and Android devices and my skills or the possibilities of the Appium itself do not allow to get stuck at least for some element of the interface to start writing code for automatic testing. So I wondered if there was any software or suggestions that I could test my game on the Unite engine directly on my physical devices.

multiple asynchronous tests and expectation

I have multiple tests and each test is testing the same asynchronous method for different results with given parameters.

I found out for asynchronous tests we have to declare an expectation, wait for expectation, and fulfil the expectation. This is fine. Each test works out correctly when done separately, but when I try to run the whole test class some tests pass and others crash or fail when they run and pass normally.

I've looked all over online for "swift 3 multiple tests with expectation" and everyone who explains expectation only ever has an example in one test method. Is it not possible to have expectations in multiple methods in the same class?

The setup in each test method is something like:

func testLoginWrongUsernameOrPasswordFailure() {

  let expect = expectation(description: "testing for incorrect credentials")

  viewModel.loginWith(username: "qwerty", password: "qwerty", completion: { loginCompletion in

      do {
        try loginCompletion()
          XCTFail("Wrong Login didn't error")
          expect.fulfill()
        } catch let error {
          XCTAssertEqual(error as? LoginError, LoginError.wrongCredentials)
          expect.fulfill()
        }
      })

      waitForExpectations(timeout: 10) { error in
        XCTAssertNil(error)
      }
}

As far as I'm aware, this is the correct use of expectation.

Meteor-coverage seems to show executed statements as not covered

I'm using the meteor-coverage package (version 1.1.4) with mocha (version 2.4.5_6) and meteor version 1.4.4.1 on Ubuntu 14.04 LTS. I have been able to produce very pretty test coverage reports, but it seems that for the client-side tests something is amiss. In order to send the coverage data to localhost:3000/coverage I have created a function called sendCoverage() which I import in my .tests.js files:

export const sendCoverage = function sendCoverage() {
    Meteor.sendCoverage(function(stats,err) {console.log(stats,err);});
};

I call this function after a block of mocha tests:

after (function () {
    sendCoverage();
});

Now, this produces test coverage reports in my localhost:3000/coverage page, but it seems as though it does not display the coverage properly. For example, I see that some statements are executed, but are highlighted in red and flagged as not covered. For example:

coverage example

It seems as though the statements get executed 11 and 12 times, respectively. However, they are not flagged as being covered and in my reports the percentage of statement coverage reflects this.

Does anyone know what I may be doing wrong and/or have experience with client-side code coverage and the meteor-coverage package?

Thanks!

Testing Angular 1.x Component using ES6 doesn't load bindings using $componentController

I have the following code

My component

class PaginationController{
    page = 1

    constructor() {
        console.log(this) // PaginationController {page: 1}
    }
}
export const PaginationComponent = {
  templateUrl: '/components/app/views/pagination.html',
  controller: PaginationController,
  controllerAs: '$ctrl',
  bindings: {
      data: '=',
      size: '<',
  }
}

Test

import { PaginationComponent } from '../src/components/app/pagination'

describe("Pagination Controller", () => {

    let controller

    beforeEach(() => {
        angular
          .module("Test", [])
          .component('pagination', PaginationComponent)
    })

    beforeEach(window.module("Test"))

    beforeEach(inject(($componentController) => {
        controller = $componentController('pagination', null, {
            data: [],
            size: 10
        })
    }))

    it("change page", () => {
        console.log(controller)
    })
})

I expect that the console.log on the contructor in the controller prints PaginationController {page: 1, data: [], size: 10} but i get PaginationController {page: 1}, so i assume that the binding is not working.

Anybody can help me to understand why?

regex test How to return only exact match

I have this code:

    var search_term = postAdminID

    // Wildcards Search
    var search = new RegExp(search_term, "i");
    sdsFilter = $.grep(sdsInfo.products, function(element, index) {
        var sted = search.exec(element.AdminID)

        return sted;

postAdminID is the index of a spesific post in an array.

element.AdminID is the corresponding index I am seraching for.

PROBLEM: Whenever I try to execute this search I get every matching index also parts of indexes matched.

Lets say I want to retrieve index #78. The above code returns: 78, 178, 278, 10078 and so forth. I only want the exact index - not every index containing the index.

I have tried .exec and test I have looked in every post here on stackoverflow that I can find.

Please help. How can I specify for regex that it should only look for the entire "string" ?

Looking for an open source Load testing tool for c# and vb.net applications

I am looking for load testing apps that are open-sourced. The load testing is done for an vb.net and c# application. Please help

Side effect exception stopping test execution

I have the following situation:

I'm testing a Django view, and I wrote a test in order to cover the flow when some exception have been raised.

The view looks like something like this:

class SomeView(View):
   # ...
   def get(self, *args, **kwargs):
       try:
           some_function_that_must_except()
       except Exception as error:
           # Flow I want to cover with test.
       else:
           # Flow already covered

And the test:

@mock.patch('some_function_that_must_except')
def test_redirect_logic_fail(self, mock_some_function_that_must_except):
    # Configuring mock
    mock_some_function_that_must_except.side_effect = Exception('Exception raised on purpose')

    response = self.client.get(
        reverse('the-view-im-testing')
    )
    # If the exception is raised then we should be redirected to
    # another view.
    self.assertRedirects(response, reverse('alternate-view'))

So good, so far, but when I run this test I get this error message:

line 1118, in _mock_call raise effect Exception: Exception raised on purpose

and then the test stops.

Why is this exception not been handled by my view?

I'm using mock 2.0.0 and python 2.7.12.

Drawing a program graph: What line is visited after a conditional or loop is not called?

Just wanted to check whether the way I am thinking is correct. Here is an example method:

1 public static boolean isCircle (int M, int m) {
2     boolean result = false;
3     if (M == m & M > 0 & m > 0) {
4         result = true;
5     }
6     return result;
7     }

If I was to draw a program graph of this method (each line being a node, their path being edges) with variables that do not satisfy the conditional e.g. M = 1, m = 0. Would the program go from line 3 -> line 6, or from line 3 -> line 5 (end of the conditional). I would think line 3 to line 6 but am unsure.

Running Cucumber tests on headless Chrome

Few weeks ago, Chrome devs have released headless version of Chrome browser. I am interested in running our acceptance tests with Cucumber. Is there any way to run them on Chrome's headless mode?

What is the difference between WebDriver listener and TestNG listener?

What is the difference between WebDriver listener and TestNG listener? How to implement the same?

caused by: undefined is not a constructor in angular 2 karma test

I am new to angular 2 karma testing. I was trying to test a simple component which has a title , an input box and a button.

I learned the basics of karma test from angular.io and was trying to test that the value contains in the input box is right or not. but was getting error "null is not an object" when i tried to get the input element in the test.

To solve that error, i gave it inside fixture.whenStable() but now having the error "undefined is not a constructor" . i don't know why that happens. Below is my component, spec.ts, html file.

Thanks.

In banner.component.html

  <h1 id="titleId" class="titleClass"></h1>
  <input id="inputId" type="text" *ngIf="name!==undefined" [(ngModel)]="name"/>
  <button id="btnId" type="button" >Click Me!</button>

In banner.component.ts

   @Component({


  selector: "app-banner",


  templateUrl: "./banner.component.html",


  providers: [AbcService],
})
export class BannerComponent {

  private abData: abData;
  private name: string;
  title = "Test Karma";
  user = {
    userName: "Nokia",
    size: 45,
  }

  constructor( @Inject(AbcService) private abcService: AbcService) {

  }

  ngAfterViewInit(): void {
      this.setAlternative();
  }

  setAlternative() {
    this.abcService.getAlternativeDetails(10752)
      .subscribe(abData=> {
        this.abData= abData;
        this.name = this.abData.name;
      });
  }

}

In banner.component.spec.ts

class AlternativeDetailsServiceSpy {
    getAlternativeDetails = jasmine.createSpy("getAlternativeDetails").and.callFake(() =>
        Promise.resolve(true).then(() => Object.assign({}, {})));
}

describe("BannerComponent", () => {

    let comp: BannerComponent;
    let fixture: ComponentFixture<BannerComponent>;
    let de;
    let el;
    let input;
    let inputEl;
    let spy: AlternativeDetailsServiceSpy;

    // async beforeEach
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [FormsModule],
            declarations: [BannerComponent], // declare the test component
            providers: [{ provide: AbcService, useValue: {} }]
        }).overrideComponent(BannerComponent, {
            set: {
                providers: [
                    { provide: AbcService, useClass: AbcServiceSpy }
                ]
            }
        }).compileComponents();  // compile template and css
    }));


    // synchronous beforeEach
    beforeEach(() => {
        let hdsSpy: AbcServiceSpy ;

        fixture = TestBed.createComponent(BannerComponent);
        comp = fixture.componentInstance; // BannerComponent test instance
        hdsSpy = fixture.debugElement.injector.get(AbcService);
        // query for the title <h1> by CSS element selector
        de = fixture.debugElement.query(By.css("#btnId"));
        el = de.nativeElement;

        // input = fixture.debugElement.query(By.css("#inputId"));
        // inputEl = input.nativeElement;

    });

    it("should check the object of bannercomponent is created", () => {
        expect(comp instanceof BannerComponent).toBe(true);
    });

    it("should be having empty value", () => {
        fixture.detectChanges();
        comp.ngAfterViewInit();
        fixture.whenStable().then(() => {
            input = fixture.debugElement.query(By.css("#inputId"));
            inputEl = input.nativeElement;
        });
    });


});

imagemagick validation and comparison of images

I have to compare a .tiff and .pdf images, can anyone help me with the commands of imagemagick tool.i want to compare the image quality parameters like resolution,size,pixel.

I want to check if two different format images are equal or not?

Thanks

Jmeter Create Content after of Create many Users(Error 403)

I simulate create 100 users random, but in the same process I want create content, but this show error. Please see the image.The post of this content show error 403, why is this? and how fix this? enter image description here

Spring Boot Exclude DataSource Configuration

I have a small application that when live, makes a database connection, and stores and persists some data.

I'm currently in the midsts of trying to write some tests, and I'm wanting to completely cut off the database part of the application, and just mock it in the tests.

The Datasource is setup with a configuration class.

@Component
@Configuration
public class DataSourceConfiguration {
    @Bean
    public DataSource myDataSource() { ... }
}

and a test boostrap that currently looks similar to

@RunWith(SpringRunner.class)
@EnableAutoConfiguration(exclude = {
    DataSourceAutoConfiguration.class,
    DataSourceTransactionManagerAutoConfiguration.class,
    HibernateJpaAutoConfiguration.class
})
public class MyTest {
}

When running the test, I can see that Spring is trying to instantiate Hibernate, and a connection to the db, I assume because of my config class. How can I stop Spring from doing this?

Fitnesse result table, why the result html tables are shown in reverse order?

I just run the 3 scenario tables for one time, first login, then make-new-claim, last logout, why the result tables are shown in reverse order??(logout, new-claim, login)

enter image description here

enter image description here

Can we disable Full text in SQL without installing any application

I want to run an application in both the ways : disabling full text feature and then enabling full text. I want to disable/enable this before running the application. How can this be done? I am using sql server 2017.

Can you please help me out with this?

System Test for a Timer which sends Emails

I have a timer which I schedule to run once a week:

http://ift.tt/2qv7JMG

at the moment I annotate a method to achieve this.

This timer sends an email:

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("", "");
                }
            }
    );

    MimeMessage message = Message.build(session, addresses);
    Transport.send(message);

I wish to write a system test for this. But how might I trigger my timer without having to wait a week? And how might I mock the smtp server?

I m using JBoss-EAP/7 but am new to this platform.

EasyMock on Android Studio

For a project, I need to use EasyMock on Android Studio, but I don't know how to install it.

Do somebody know how to install EasyMock on Android Studio ?

Thanks in advance.

dependency spring-boot-starter-test not inherited in multiple module maven project

In my multi-module maven project, all modules have a dependency of my own "common" module, eg, module "A" have this dependency "common". And the "common" module has a spring-boot-starter-test dependency. However, when I write unit test in this "A" module, it shows that the test dependency not imported. And then I check the dependencies and found that the spring-boot-starter-test is not imported. I want to ask why? In my sense, module "A" ref "common", "common" ref spring-boot-starter-test , so the module "A" should ref spring-boot-starter-test, but the fact is not that. By the way, in spite of this spring-boot-starter-test other dependencies works well via the hirachy. Does anyone know why it is? Thank you in advance.

Test only untested modules with Maven

I am working on a java project with multiple modules using maven. Each of these modules has its own set of tests. Sometimes i run all tests on many threads. In the event of a failure in one of the modules, it is sometimes hard to determine which modules are left to be tested since they were being tested all at the same times (Maven shows me a list of all successful/unsuccessfull modules and I sometime have few successfully tested modules at the beginning and the end). In that case, the option "-rf" doesn't solve the problem.

I would like to know if there is a way in maven to resume testing only the untested modules.

Accelerometer, Android, Simulate replace current Data with Old one

  1. I need a way to replace real accelerometer data from phone sensor with other one old data (x,y,z) that currently i have at Excel table and array at Android. Maybe i need to write my own class Sensor or?

    Because i want to test my app with them

  2. Does i calculate linear acceleration right.

    private float timeConstant = 0.18f;
    private float alpha = 0.7f;
    private float dt = 0;
    // Timestamps for the low-pass filter
    private float timestamp = System.nanoTime();
    private float timestampOld = System.nanoTime();
    
    

    (...)

    @Override public void onSensorChanged(SensorEvent sensorEvent) { Sensor accSensor = sensorEvent.sensor;

    if (accSensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        System.arraycopy(sensorEvent.values, 0, this.accelerationOnAxis, 0, sensorEvent.values.length);
    
        x_accelerometer = sensorEvent.values[0];
        y_accelerometer = sensorEvent.values[1];
        z_accelerometer = sensorEvent.values[2];
        //timestampOld = timestamp;
        timestamp = System.nanoTime();
    
        float deltaTime = timestamp - timestampOld;
    
        dt = 1 / (count / ((deltaTime) / 1000000000.0f));
    
        count++;
    
        alpha = timeConstant / (timeConstant + dt);
        // long tDelta = currentUpdate.getTime() - lastUpdate.getTime();
        // long t = 1 / (2 * Math.PI * fc);
        //alpha = t / (t + tDelta);
    
        x_gravity = alpha * x_gravity + (1 - alpha) * x_accelerometer;
        y_gravity = alpha * y_gravity + (1 - alpha) * y_accelerometer;
        z_gravity = alpha * z_gravity + (1 - alpha) * z_accelerometer;
    
        x_linear_acceleration = x_accelerometer - x_gravity;
        y_linear_acceleration = y_accelerometer - y_gravity;
        z_linear_acceleration = z_accelerometer - z_gravity;
    
        gravityOnAxis = new float[]{x_gravity, y_gravity, z_gravity};
        linearAcceleration = new float[]{x_linear_acceleration, y_linear_acceleration, z_linear_acceleration};
    
        int length = linearAcceleration.length - 1;
        Log.d("LinearAccelOnAxes", "on x-" + x_linear_acceleration +
                "on y-" + y_linear_acceleration +
                "on z-" + z_linear_acceleration);
    
        allAccelData.add(linearAcceleration);
    
    

    /// } } currentAcceleration = (float) (Math.pow(x_linear_acceleration, 2) + Math.pow(y_linear_acceleration, 2)+ Math.pow(z_linear_acceleration, 2));

}

Thank You

Java Book Testing

i'm looking for some good (up-to-date) java books that explains different testing methods with examples. In detail i'm looking for books that give inside in not only unit testing (Junit) but also in integration tests, functional tests, system tests, and other testing methods. I also like to learn how to test systems with database connections, incoming file transfers and other more complex mechanics.

I hope you can help me. - Dominik -

jmeter run in headless with 5000 user, which is better option to save results in CSV or XML or JTL

Is it good to save the data, when jmeter running in high load and distributed load testing. we are running the jmeter with 5000 users in AWS server. need to report the results of below.

  1. throughput over time and over active users.
  2. response time over TPS.
  3. aggregate report.

So which is better option to save CSV or XML or JTL.

Test actor in akka by java and have ActorInitializationException

I want using from actor test in create actor sample code.but by run actor test throws ActorInitializationException.i am using junit test my class code in under: public class Worker extends AbstractActor {

private ActorSystem system = ActorSystem.create("worker");;
private Props props = Props.create(Worker.class , system.guardian().toString());
private ActorRef actor = system.actorOf(props);

@Override
public void preStart() {
    System.out.println("worker actor started");
}

@Override
public void postStop() {
    System.out.println("worker actor stopped");
}



@Override
public Receive createReceive() {
    return receiveBuilder()
            .matchAny(x -> getSender().tell(x, getSelf()))
            .build();
}


@Test
public void testMain() throws Exception {
    Future sFuture = ask(actor, "ping" , 1000);
    System.out.println("First : " + sFuture);

}


public static void main(String [] args) {
    List<Long> numbers = new ArrayList<>(10);
    for(int i = 0 ; i < 10 ; i++) {
        numbers.add((long) (i+1));
    }
    ActorSystem system = ActorSystem.create("worker");
    for(Long number : numbers) {
        Props props = Props.create(Worker.class , number.toString());
        ActorRef actor = system.actorOf(props);
        actor.tell(number , ActorRef.noSender());
    }
}

}

and exception is:`

akka.actor.ActorInitializationException: You cannot create an instance of [ir.dotin.alm.akka.worker.Worker] explicitly using the constructor (new). You have to use one of the 'actorOf' factory methods to create a new actor. See the documentation.

at akka.actor.ActorInitializationException$.apply(Actor.scala:192)
at akka.actor.Actor$class.$init$(Actor.scala:467)
at akka.actor.AbstractActor.<init>(AbstractActor.scala:132)
at ir.dotin.alm.akka.worker.Worker.<init>(Worker.java:17)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:187)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:236)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:233)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)

lundi 29 mai 2017

Jmeter Variables Random in User and Email

I need to do test performance, simulate 100 users diferent, but How do I make random variables the user and e-mail?

enter image description here

integration test cases for chat program

Can someone explain to me what would be some test cases for integration testing for a chat program? I have login, registration and send message for unit testing already but im stuck in the integration part.

Simulating abnormal termination in pytest

My multithreaded app suffered from a bug where any abnormal termination of the main thread (e.g., an uncaught exception or some signals) caused a deadlock on one of the other threads, and prevented the process from cleanly exiting. I fixed that issue, but I wanted to add a test to prevent regression.

However, I cannot figure out how to simulate abnormal termination in pytest.

If I just raise an exception in a test, the abnormal termination is simulated perfectly, but of course pytest reports an error even when everything works as intended.

On the other hand, if I surround the raising of an exception with pytest.raises context manager, the main thread is not abnormally terminated since pytest catches the exception.

How would you manage a test database for running tests against it?

This question is probably not Jenkins-only. However I am thinking about this concept because of we want to implement Jenkins CI into our workflow, so this would be a good place to start.

So let's start by giving some context: I'm a Jenkins newby. I work for an internet agency and work on projects from Drupal 7 and 8 to 100% custom legacy projects. All of them being websites, build on PHP and Mysql.

Some Jenkins / Testing concepts are clear to me, others still vague or even unclear. We have written tests in the past, but we didn't consider all facets as good as we are trying to right now.

I now came to the point of thinking about how you would manage a database to run tests against it.

Looking at codeception's Db subject, they explain that a mysql dump will be loaded before running each test, so that the tests always run against a clean database.

Implementing that in our workflow I would think of something like this:

1) Let's say I start developing a new feature on a new Git branch.

2) I would first make sure my repository is up-to-date and run all patches/config-exports against my database, so that also my database is up-to-date

3) I would then first make a database dump from the current state of the database and make sure that no unnecessary data like logs, etc. are in that dump.

4) I would then start developing and any structural database changes must be in patchfiles, or - in the case of Drupal 8 - in config exports.

5) Then finally when everything has been committed and a merge request is being made, the test stack will load the clean database in a test environment, run all patches/config-imports against it, and finally run the tests.

Could you guys please tell me whether this is a good scenario or give me a better one? All feedback will be greatly appreciated since I'm absolutely new to this concept.

How to set test group to @Test methods dynamically using TestNG?

I want to set group to a particular @Test method at runtime depending on some condition

Suppose I have the following classes

public class MyTest1{
  @Test
  public void test1(){
    System.out.println("test1 called");
  }
}

public class MyTest2{
  @Test(groups={"group1"})
  public void test2(){
    System.out.println("test2 called");
  }

  @Test(groups={"group2"})
  public void test3(){
    System.out.println("test3 called");
  }
}

Now while running test I am sending "-groups group1" or "-groups group2" to TestNG in command line. So testng is running either test2() or test3() depending on the group name passed. Now my requirement is to run test1() that is not supposed have any groups attached. Whatever group I provide to testng runner this test1() should be run every time. I tried with implementing alter method of IAlterSuiteListener but I could not get all the test methods including which are not considered to run. So I could not set the group name at runtime.

So is there any other way to set groups to @Test methods (having no groups defined) at runtime?

Need help in designing Rest Api TEST framework using mocha, chai and request npm module

I am developing a NodeJS RestAPI test framework using REQUEST npm module for making http calls, MOCHA as an test framework, CHAI for assertions.

I seek help from the community, inorder to design the framework more beautifully. Please share your thoughts regarding the ideal framework structure.

If possible, define the structure giving a api example

How to automate twilio outgoing call testing

Looking to add Twilio to one of the project. Managed to setup outgoing calls with But how can I automate the testing of these outgoing call scripts ? or testing the simple IVR that I have setup.

How to mock activity dependencias in an instrumentation test

I want to get a reference to my activity before it is created in order to inject some mocks.

So I have my activity test rule like:

   ActivityTestRule mActivityRule = new ActivityTestRule<MainActivity>(MainActivity,class, true, false)

I know that ActivityTestRule has a beforeActivityLaunched callback, but there I cant get any reference to my activity (is null there).

So if I do:

@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule(
        MainActivity.class) {
    @Override
    protected void beforeActivityLaunched() {
        super.beforeActivityLaunched();
        MainActivity act = (MainActivity)getActivity();
         //Here act is null

I cannot get a reference to my activity in the setUp method of my test class either. Activity reference is ready only when I do rule.launchActivity(), but then Activity is executed and I cannot pass any dependencies before. I know that I can use dagger for that, but I want to avoid it for this case. Is there any way to prepare the activity dependencies without dagger before it is launched?

how to test an executable in .NET

Every time, when I deal with writing Tests in .NET (C#), I read, you can test DLLs only. But my app hasn't any DLLs and I want test some controllers and behaviours too. How it is possible, without creating an DLLs project? Is it possible?

Hints are welcome.

Which framework i Use for automation for kendo-UI and React Based Application

I am new for testing the Kendo-UI and React Application first time. -> I tried with selenium but because of dynamic DOM structure of React Application, it is difficult to automate and now i switch to protractor but it is also giving me problems or failure of element not found, locator not visible etc.

So, i want your suggestion for automating an application based on kendo-UI and React Application.

Can I test cross-browser javascript via the command line?

Firefox has the JSShell for SpiderMonkey. Do the other major browsers Chrome and Safari have a command-line interface to their javascript engines? If so, this would be a great lightweight way to test javascript to ensure that it runs cross-browser without having to open a full browser.

Workaround for Java Concordion substring ("contains")

As i see, Concordion test framework makes only exact strings/numbers matching.

Is there any workaround to test the result contains some substring?

For instance, i test a service returns an error in format ERROR 123, and the test should be valid for any error number.

Testing the quality, format and sizing of an image

For a website I am building, I need a solution to test that a given Image (upload by an user) meet certain specification :

  • It can be a Scanned image, Smart phone pictur, Digital upload or Web Camera picture
  • at least 8MP
  • Scanned images should be over 300 dpi in resolution and the size of scan reduced to the size of the document. Passport 130mm x 90mm, Driving Licence 90mm x 55mm and Euro ID 130mm x 90mm.
  • Not blurred
  • Colour Image
  • PDF, JPG or PNG file type
  • Clear edges
  • 90 degree angle (bird’s eye view)
  • Size of the document between 102 k and 3 M

Do you know how I can test all this specification ? Java will be the preferred language, but I am open to others languages.

importing python module for development

I would like to know what is the best way to work on an existing python module with anaconda for new version development.

Is it possible to have to different paths: one where standard anaconda is stored, and one where the dev of the new version is done; And with a simple python command select wich files to select to dev and test ?

# std command
from my_module import function_x 

# module development command
import2( 'my_file', 'function_x')

# or better way ... ?

So I could have the standard import command and then overwrite the python env so it will look for function_x in my dev environnment. Is that the usual way or there is a standard frame to do that ?

dimanche 28 mai 2017

unable to install testing for eclipse mars

I getting error message that authentication required on site http://best. Com/eclipse Tried from eclipse marketplace and also through install new software option

Websocket API calls batch testing

Are there any tools readily available to test web socket based API calls and responses in multiples? I am looking for tools that test multiple calls at a time rather than browser based plugin clients which only test single call/response at a time. This would be more of an automated solution. If anyone can share sample code that would be appreciated.

How to test getter that returns a list of custom objects?

Ok so lets say we have the following simple class:

 public class Employees{


        List<Person> personsList;
        private int numberOfEmployees;

        public void Employees(){

        //constructor

        }

        //getters & setters

        public List<Person> getPersons(){
            return personsList;
        }

          public void addNewEmployee(Employee employee){

        this.numberOfEmployees.add(employee);

    }

    }

And i want to test the getter that returns a list of Person objects(using mockito)

I am doing something like:

@Test
public void getPersonsTest() throws Exception{
    Employees.addNewEmployee(employee); //where employee is a mocked object

    assertEquals(Employees.getPersons(),WHAT SHOULD I PUT HERE??);


}

Any ideas?

Autowired implementation based on profile Spring Boot

I am developing a REST API with Spring Boot.The problem it's that I have one interface and two implementations and I want to test only with the mock implementation.

Interface CRMService 

@Service
CRMServiceImpl

@Service
CRMServiceMock

Implementations: the first one is the real integration with the backend and de second is a mock for testing purposes, what's the best approach? Integration test or test based on the active profile ? If I need to autowire a service based on profile what's the best practice?

acunetix security bug "long password denial of service"

hello guys i run my asp application in server and check this security test with acunetix my application has 1 high security bug ("long password denial of service") i try some solution to fix it :

-add asp validator with 15 character limitation
-check password length with java script
-check password length on server side
-put an captcha on my login page

But had no effect and still gives an error "long password denial of service"

Please Help me ! whats wrong!? Do you think that acunetix mad

samedi 27 mai 2017

I have written this test returning status code 404 while there are other same tests but they are running OK and returning status code 200

Do not know why this test returning 404 instead of 200. Plz help.

def test_portal_day_archive_view(self):
    self.entry = Entry.objects.create(pub_date=self.now, is_active=True, headline='active', slug='b')
    url = reverse('portal:archive_day', kwargs={'year': self.entry.pub_date.year,
                                                'month': self.entry.pub_date.strftime('%b').lower(),
                                                'day': self.entry.pub_date.strftime('%d')}
                )
    self.assertEqual(200, self.client.get(url).status_code)

Is .lower() with day is necessary on this url?

http://ift.tt/2s23KUO

Is putting .lower() with day is necessary? What does day do with the .lower()?

PROTRACTOR: Integrate jasmine-spec-reporter in slack?

I installed jasmine-spec-reporter to replace the default DOT reporter.

Everything is great running, but I want to send the texts I'm seeing in the terminal directly to slack. What is the payload that I should send to slack? and is it possible?

Selinum Chroumium Driver not Loding

does anybody know the Problem ?? enter image description here

it started once nad then this problem in the Picture.

[01:53:15,339] INFO [CheckOut-0] - ####### Test 'MyTestCases.CheckOut' started Starting ChromeDriver (v2.9.248304) on port 17682 May 26, 2017 1:53:16 AM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end [0.183][WARNING]: PAC support disabled because there is no system implementation May 26, 2017 1:53:18 AM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: OSS [01:53:20,832] INFO [CheckOut-0] - ####### Test 'MyTestCases.CheckOut' finished after 5491 ms [01:53:20,838] INFO [CheckOut-0] - Cleaning up ...

vendredi 26 mai 2017

Java Selenium pararel test cases running

Can not run TC in parallel. I set up parallel TC running in testng.xml file. It opens 4 instances of browser but test cases are failed. Looks like it creates just one instance of browser session (or something like that) so it tries to do all 4 test in one instance.

How to modify my settings to run TCs in parallel successfully?

I have set up driver in the following way:

package MainSettings;

import Pages.StartPage;
//import TrackReporting.CaptureScreenShotOnFailureListener;
import TrackReporting.LoggingEventListener;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.events.WebDriverEventListener;
import org.testng.annotations.*;

/**
 * Created by serhii.kaihorodov on 1/4/2016.
 */
//@Listeners(CaptureScreenShotOnFailureListener.class)
public class Settings {
    protected static WebDriver driver;
    protected String baseURL = "https://www.ukr.net";
    private static final WebDriverEventListener eventListener = new LoggingEventListener();
    protected StartPage mainPage;

    @BeforeMethod
    public void setUp()
    {
        System.setProperty("webdriver.chrome.driver", "D:\\Programming\\Java Automation\\ukr.net_test_cases-master\\chromedriver.exe");
//        driver = new EventFiringWebDriver(new FirefoxDriver()).register(eventListener);
        driver = new EventFiringWebDriver(new ChromeDriver()).register(eventListener);
        getDriver().get(baseURL);
        mainPage = new StartPage();
        driver.manage().window().maximize();
    }

    @AfterMethod
    public void tearDown()
    {
        driver.quit();
    }

    public static WebDriver getDriver()
    {
        return driver;
    }
}

My testng.xml file is the following:

<!DOCTYPE suite SYSTEM "http://ift.tt/19x2mI9" >

<suite name="My_auto_test" verbose="2" parallel="methods" thread-count="4">

    <test name="ukr.net">
        <classes>
            <class name="TestCases.TestCases_block_1"/>
        </classes>
    </test>

</suite>

pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://ift.tt/IH78KX"
         xmlns:xsi="http://ift.tt/ra1lAU"
         xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
    <modelVersion>4.0.0</modelVersion>
    <groupId>MySel20Proj</groupId>
    <artifactId>MySel20Proj</artifactId>
    <version>1.0</version>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.9.6</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.9.8</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20</version>
                    <configuration>
                        <parallel>tests</parallel>
                        <threadCount>4</threadCount>
                        <suiteXmlFiles>
                            <suiteXmlFile>KayTC/src/testng.xml</suiteXmlFile>
                        </suiteXmlFiles>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

My several test cases are:

package TestCases;

import MainSettings.Settings;
import org.testng.annotations.Test;

import java.io.IOException;

/**
 * Created by serhii.kaihorodov on 1/4/2016.
 */
public class TestCases_block_1
{
    public class TestCases extends Settings
    {
        @Test (priority=0)
        public void login()
        {
            mainPage.login("kay444415@ukr.net", "06011988");
        }

        @Test (priority=0)
        public void sinoptik_link_is_present1()
        {
            mainPage.login("kay444415@ukr.net", "06011988").sinoptik_link_is_present();
        }

        @Test (priority=0)
        public void autosale_link_is_present1()
        {
            mainPage.login("kay444415@ukr.net", "06011988").autosale_link_is_present();
        }
  }

The Case of the Mysterious Disappearing Test Database

The Problem

I work on a Rails 3.2.2 application that's in the process of being upgraded out of the stone age. We're running a MySQL database and, up until this past week, everything's worked exactly as expected. That is, until the mystery began...

A few days ago, I went to go run my local test suite (Test::Unit) and saw an error that suggested my test database no longer existed. So I logged into MySQL and saw that, in fact, it didn't. Gone! Poof!

No error messages, no warnings. Nothing. Just gone.

I recreated the database and didn't give much thought to it. I figured that - somehow - I'd deleted it by accident.

Two days later, the exact same thing happened to my coworker. Test database vanished without warning.

And today, it happened to another developer on my team.

I can't find anything about this anywhere. No SO posts, no blog articles, nada.

Has anybody else experienced this? Does anyone have any idea of what could be causing it, or of what steps we could take to investigate?

Many thanks.

The Stack

  • Rails 3.2.22.2 (using the mysql2 adapter gem)
  • mysql 14.14 Distrib 5.6.26, for osx10.10 (x86_64) using EditLine wrapper

Null object after using @Inject

I am trying to use Java Dependency Injection in my functional test. While trying to run the test I keep getting the dependency as null. The constructor of this dependency will just start a wiremock server. Can someone please help me find what is wrong?

MockService - that gets injected

public class MockService {

    public MockService() {
        this(8080, 9443);
    }

    public MockService(int port, int httpsport){

        wireMockServer = new WireMockServer(config);
        wireMockServer.start();    
    }
}

Functional test where I am injecting:

public class SampleResourceFunctionalTest {

    @Inject
    MockService mockService;

    @BeforeClass 
    public void init() {

        mockService.calls();

     }....


}

I keep getting a null for mockService in the init() method. Why is the mockService not getting injected?

Thanks for your help here

I can not run my JUnit tests anymore

I have a project with two modules and starting this morning whenever i try to run my JUnit tests on both modules i get this error in my gradle build

Error:Execution failed for task ':usecases:compileDebugUnitTestJavaWithJavac'. java.lang.reflect.InvocationTargetException

usecases is one of my modules.

Thanks in advance

Testing React component with dynamic import (Enzyme/Mocha)

I'm trying to test a React component using Mocha and Enzyme that uses a dynamic import to load a module.

When I try to test the logic that relies on the dynamic import I get incorrect results. The problem is that the async functions don't finish before the test finishes so I can never get accurate results.

How can I handle this scenario?

Component

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

// styles

import styles from './PasswordStrengthIndicator.scss';

class PasswordStrengthIndicator extends React.Component {
  static defaultProps = {
    password: undefined,
    onPasswordChange: undefined,
  }

  static propTypes = {
    password: PropTypes.string,
    onPasswordChange: PropTypes.func,
  }

  constructor() {
    super();

    this.state = {};
  }

  componentWillMount() {
    this.handlePasswordChange();
  }

  componentWillReceiveProps(nextProps) {
    const password     = this.props.password;
    const nextPassword = nextProps.password;

    if (password !== nextPassword) {
      this.handlePasswordChange();
    }
  }

  render() {
    const strength = this.state.strength || {};
    const score    = strength.score;

    return (
      <div className={ styles.passwordStrength }>
        <div className={ classNames(styles.score, styles[`score-${score}`]) } />
        <div className={ styles.separator25 } />
        <div className={ styles.separator50 } />
        <div className={ styles.separator75 } />
      </div>
    );
  }

  // private

  async determineStrength() {
    const { password } = this.props;
    const zxcvbn = await import('zxcvbn');

    let strength = {};

    if (password) strength = zxcvbn(password);

    return strength;
  }

  async handlePasswordChange() {
    const { onPasswordChange } = this.props;
    const strength = await this.determineStrength();

    this.setState({ strength });

    if (onPasswordChange) onPasswordChange(strength);
  }
}

export default PasswordStrengthIndicator;

Test

describe('when `password` is bad', () => {
  beforeEach(() => {
    props.password = 'badpassword';
  });

  it.only('should display a score of 1', () => {
    const score = indicator().find(`.${styles.score}`);

    expect(score.props().className).to.include(styles.score1); // should pass
  });
});

Testing store method in Controller

I am new to testing.

I have controller in Laravel and I want to test the store method.

This is my controller.

class ClientsController extends Controller
{
    protected $client;

    public function __construct(App\Client $client)
    {
        $this->client = $client;
    }

    public function index()
    {
        $clients = $this->client->all();

        return view('clients::index')->with('clients', $clients);
    }

    public function create()
    {
        return view('clients::create');
    }

    public function store(App\Requests\CreateClientRequest $request)
    {

        $this->client->create( $request->only(['name', 'head_person','address','primary_email','contact_no']) );

        return redirect()->route('clients.show', ['id' => $this->client->id]);
    }

    public function show($id)
    {
        $client = $this->client->find($id);
        return view('clients::show')-with('client',$client);
    }
}

I have written a test but it fails. I cannot find out where i am wrong.

Here's the test

class ClientsControllerTest extends TestCase
{
    use DatabaseMigrations;

    protected $user;

    public function __construct()
    {
        $this->clientsMock = \Mockery::mock('Eloquent','App\Client');
    }

    /**
     * 
     * @before
     */
    public function runSetupBeforeClass()
    {
        parent::setup();

        $this->app->instance('App\Client',$this->clientsMock);
    }

    public function tearDown()
    {
        \Mockery::close();
    }

    /**
     * 
     @test
     */
    public function shouldAddsNewClient()
    {
        $client = factory(Client::class)->make();

        Input::replace($input = [
                            'name'  => $client->name,
                            'head_person' => $client->head_person,
                            'address'   => $client->address,
                            'primary_email'  => $client->primary_email,
                            'contact_no'   => $client->contact_no,
                        ]);

        $this->clientsMock
            ->shouldReceive('create')
            ->once();
            ->with($input);

        $response = $this->post('/clients');    

        $response->assertStatus(302)
                ->assertRedirect(route('clients.show'));
    }

Please help me with this. How should I write my tests for the store method.

Where should I place test utility classes in Java?

What is the best practice for placing TestUtil classes, such as MockFooClass?

My hunch is placing them under src/test/java, and not src/main/java.

Is there away to start/stop a mock service via groovy script as one of the groovy test steps?

I'd like to be able to start mock service in SOAPUI on test case setup script and close it through tear down script. I figured out how to start the service in setup script:

def project = null
def projectName = "myproject"
def workspace = testRunner.testCase.testSuite.project.getWorkspace();

//if running Soapui
if(workspace != null){
    project = workspace.getProjectByName(projectName)
}
else {
    log.error("Can't find workspace")
}
if (project != null) {
    log.info("Project " + projectName + " located!")    
    project.getMockServiceByName("myMockService").start(); 
     log.info("Project myMockService started!")
} else {
    log.error("Can't find " + projectName + " project, please start mock service manually") 
}

But having difficulties obtaining a reference to already running mock service in order to stop it. Any suggestion what should I script in tear down script to stop the service? enter image description here

Python mocking logging while retaining log output

I have a series of unit/integration tests which using the python logging module. I would like to test that the right things are logged when appropriate which I can achieve using the mock module as follows:

@mock.patch('logging.Logger.info')

However, when I do this the actual logging is stopped (for obvious reasons!) and this is useful for me to debug why my tests are working etc.

My question is as follows: Is there a way in why I can mock out logging calls so I can assert they have been called with the expected arguments but still keep the logging functionality?

Cheers, Jack

Grunt Karma PhantomJS - SyntaxError: Unexpected token '<'?

I keep getting an error when running this in my terminal (at the location of gruntfile.js):

grunt karma

The solutions here either didn't work or are no longer an option - http://ift.tt/2rYnrgz

Here is the output:

Running "karma:unit" (karma) task
26 05 2017 13:43:15.838:INFO [karma]: Karma v1.7.0 server started at http://0.0.0.0:8082/
26 05 2017 13:43:15.840:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
26 05 2017 13:43:15.848:INFO [launcher]: Starting browser PhantomJS
26 05 2017 13:43:15.955:ERROR [phantomjs.launcher]: Fontconfig warning: ignoring C.UTF-8: not a valid language tag

26 05 2017 13:43:16.130:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 9TxdacwF4rc7mUB0AAAA with id 76282796

PhantomJS 2.1.1 (Linux 0.0.0) ERROR
SyntaxError: Unexpected token '>'
at app/client/app.js:2


PhantomJS 2.1.1 (Linux 0.0.0) ERROR
SyntaxError: Unexpected token '>'
at app/client/paths/home/homeCtrl.js:2

Here is my code:

karma.config.js

module.exports = function(config) {
    config.set({

    frameworks: ['jasmine'],


    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'app/**/*.js',
    ],

    port: 8082

    browsers: ['PhantomJS'],

    plugins: [
       'karma-phantomjs-launcher',
       'karma-jasmine',
       'karma-ng-html2js-preprocessor'
    ],

    logLevel: config.LOG_INFO,
})};

grunt test block for karma in gruntfile.js

karma: {
    unit: {
        configFile: 'karma.config.js',
        singleRun: true,
    }
}

homeCtrl.spec.js

describe('HomeCtrl', function() {
    beforeEach(module('myApp'));

    var HomeCtrl;
    beforeEach(inject(function($controller){ 
        HomeCtrl = $controller('HomeCtrl');
    }));

    describe('message', function() {
        it('should read hello', function() {
            expect(HomeCtrl.message).toBe('Hello');
        });
    });

});

homeCtrl.js

angular.module('RevisionApp')
    .controller('HomeCtrl', ($scope) => {
        $scope.message = 'hello';    
    })

Here is the folder structure: http://ift.tt/2roRsJ3

Any input would be much appreciated, thanks.

Automating github login through Selenium Webdriver

Hi guys I am trying to automate the github login process through selenium web driver in java , everything is fine and okay except for the very first time when the user does not exist github asks the user to allow the access as shown in the picture

enter image description here

I am trying to find out that if the title of the window is authorize application than run a specific flow and if not run the usual flow but its not finding out the title and the test fails on the authorization screen and if I try to find the authorize green button it says the element is not enabled

The code is below for help

package com.silexica.selenium.tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class GitHubLoginTest {

    @Test
    public void githubLogin() {

        // Set our gecko driver
        System.setProperty("webdriver.gecko.driver", "geckodriver");

        // setting up the firefox driver
        WebDriver driver = new FirefoxDriver();

        // Open website
        driver.get("");

        // wait for the google icon button to load
        WebDriverWait githubbuttonwait = new WebDriverWait(driver, 10);
        WebElement githubloginbutton = githubbuttonwait.until(ExpectedConditions
                .visibilityOfElementLocated(By.xpath("/html/body/div/div/div/div/div/form/ul/li/a[2]/img[2]")));

        // click the button if present
        githubloginbutton.click();

        // Find the email form field
        WebDriverWait githubemailfieldwait = new WebDriverWait(driver, 10);
        WebElement githubemailfield = githubemailfieldwait.until(ExpectedConditions
                .visibilityOfElementLocated(By.xpath("/html/body/div[3]/div[1]/div/form/div[3]/input[1]")));

        // Type the random email to the form
        githubemailfield.sendKeys("");

        // Find the password form field
        WebDriverWait githubpasswordfieldwait = new WebDriverWait(driver, 10);
        WebElement githubpasswordfield = githubpasswordfieldwait.until(ExpectedConditions
                .visibilityOfElementLocated(By.xpath("/html/body/div[3]/div[1]/div/form/div[3]/input[2]")));

        // Type password to the form. This needs not be unique.
        githubpasswordfield.sendKeys("");

        // find the sign up button
        WebDriverWait githubpasswordbutton = new WebDriverWait(driver, 10);
        WebElement passwordfieldsignupbutton = githubpasswordbutton.until(ExpectedConditions
                .visibilityOfElementLocated(By.xpath("/html/body/div[3]/div[1]/div/form/div[3]/input[3]")));

        // click the sign up button
        passwordfieldsignupbutton.click();

        // verify that the authorization window has the given text
        if ((new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driverObject) {
                return driverObject.getTitle().equals("Authorize application");
            }
        })) {

            // find the allow access button button in google password window
            WebDriverWait githubpasswordbutton2 = new WebDriverWait(driver, 10);
            WebElement passwordfieldsignupbutton2 = githubpasswordbutton2
                    .until(ExpectedConditions.visibilityOfElementLocated(
                            By.xpath("/html/body/div[4]/div[1]/div[2]/div[1]/div[2]/div[1]/form/button")));

            // click the button
            passwordfieldsignupbutton2.click();

            // verify that we have logged into the dashboard
            (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver driverObject) {
                    return driverObject.getTitle().equals("Silexica | Dashboard");
                }
            });

            driver.quit();

        } else {

            // Verify that whether we have logged into the dashboard and
            // continue the normal flow
            (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver driverObject) {
                    return driverObject.getTitle().equals("Silexica | Dashboard");
                }
            });

            // close the browser
            driver.quit();

        }

    }

}

Any suggestions or improvements

How to test a function call from a different module

There are probably lots of similar questions here but I still don't understand how it's done.

Let's say I have the following trivial module:

defmodule ModuleOne do

  def do_something(argument) do
    argument
    |> do_first_thing()
    |> do_second_thing()
    |> ModuleTwo.do_something()
  end

end

Now, I have ModuleTwo covered with tests so it doesn't make sense to duplicate that testing logic. Also it's not Twitter API module or something of the kind so I dont think it's a good idea to come up with a compile-time mock module ( as far as I can see, it's a good idea in case cases, like HTTP calls but doing that for every external module call will obviously turn into a mess ) and also I don't want to pass a function as an argument just for the sake of testing ( especially if I have calls to multiple external modules ) because it messes up the interface with unnecessary things.

Also people suggest not to use mocks, like the meck library, which is the most obvious decision here, but I don't understand why ...

Anyway, what would be a good way to test this module considering all the suggestions above?

Thank you

Node testing - rewire and fakeredis on object oriented app

So I'm attempting to test an app that uses a redis backend and an OO type framework. Using models in the format below for various objects. I've provided a very cut down version of one of the models below.

class Tld {

/**
 * Creates an instance of Tld
 * @constructor
 * @param {string} tld The tld name
 */
constructor(tld) {
    this.identifier = tld
}


/**
 * Returns a promise that is fulfilled with an array of
 * tlds from redis tlds(zset) key
 *
 * @static
 * @param {Integer} [limit=-1] Number of tlds to return
 * @returns {Promise<Array>}
 *
 * @memberof Tld
 */
static getAll(limit = -1) {
    return new Promise((resolve, reject) => {
        redisClient.zrange("tlds", 0, limit, (err, tlds) => {
            resolve(tlds)
            reject(err)
        })
    })
}
/**
 * Add tld to the list of tlds
 *
 * @static
 * @param {String} tld
 * @returns {Promise<void>}
 *
 * @memberof Tag
 */
static addToList(tld, weight){
    return new Promise((resolve)=>{
         redisClient.zadd(`tlds`, weight, tld, ()=>{
             resolve()
        })
    })
}
}

This app is bootstrapped on load to populate redis with data from various APIs and other things, with a function similar to

Tld=require('../models/tld')
// tlds = loadDummyData()
// // tlds schema retreived from the dummy file
for(tld of tlds){
    tld = new Tld(tld)
    promises.push(Tld.addToList(tld.identifier, weight))
}

return Promise.all(promises)

It's all functional and cool, so I'm currently writing tests for the app, with mocha and chai. With a live redis instance, all is well, however I want to implement CI and I don't want to run redis on my build/test server, so I am looking to replace the redis instance using rewire and fakeredis.

My efforts so far include attempting to rewire the redis client on the bootstrap file and on the model, and bootstrapping (with dummy data) to a fake redis instance.

// Import testing modules
var assert = require('assert');
var chai = require('chai');
var expect = chai.expect;
chai.use(require('chai-ajv-json-schema'))
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);


// rewire redis to mocked  redis
var rewire = require("rewire");
var client = require("fakeredis").createClient();
var bootstrap = rewire('../bin/bootstrap')

var Tld = rewire('../models/tld')

bootstrap.__set__('redis', client)
Tld.__set__('redisClient', client)

bootstrap() // Would move this to a before() function in reality.


describe('Tld', function() {  
  describe('getAll', function() {
    it('should get all TLDs', function() {
        var results = Tld.getAll()

    return(expect(results).to.eventually.be.validWithSchema(
       tld_getall_schema))

    });
  });
})

However, in this case the TLD model is using the fake redis instance (Which is empty of data) but (I assume?) because the bootstrap function is including the Tld Model itself (Which will not be rewired at the point of including?) it's attempting to bootstrap to a live redis instance and is obviously erroring out.

1) Uncaught error outside test suite - Uncaught Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379

so i threw a horrific attempt at a hack on:

bootstrap.__set__('redis', client)
Tld.__set__('redisClient', client)
// Inject rewired Tld model back into bootstrap:
bootstrap.__set__('Tld', Tld)
// bootstrap it.
bootstrap()

Which did basically no good at all.

So, How can I either replace the entire redis connection with rewire (without modifying my app code with a redis wrapper for example, because testing should be code-independant) Or, How can I fix what i'm doing here with regards to the bootstrapping to fake-redis.

Thanks for reading, hopefully you clever people can help me with a simple way to test the app :)

Would testing my Java Servlet be neccessary?

I just wanted to ask if it is necessary to test the java servlet that calls another java method (in another file I might add) to do the bulk of the work.

Like for instance, my java servlet currently only is being used to get parameters and displaying the results of the method that was called in html format. So I am only planning on testing my main java file that does all the work!

I am not very familiar with testing so if there would be specific ways to test this simple Java servlet, please let me know!