mercredi 31 août 2016

ServletUnit RequestDispatcher forward() / include() methods AbstractMethodError

I'm doing a java web app with a servlet and I wanted to write some tests to check its functionality (ex. authorization form). I hadn't been using any framework, just bare java in eclipse with tomcat 7.0

I've run into an error while trying to test authorization input. The app would check the login-password pair and then redirect using RequestDispatcher.forward() or RequestDispatcher.include() methods. But when executing them it throws an error with the following stack trace:

            java.lang.reflect.Inv­ocationTargetExceptio­n

            at su­n.reflect.NativeMetho­dAccessorImpl.invoke0­(Native Method)

            at su­n.reflect.NativeMetho­dAccessorImpl.invoke(­Unknown Source)

            at su­n.reflect.DelegatingM­ethodAccessorImpl.inv­oke(Unknown Source)

            at ja­va.lang.reflect.Metho­d.invoke(Unknown Sour­ce)

            at en­tryPoint.Dispatcher.d­ispatch(Dispatcher.ja­va:166)

            at en­tryPoint.Dispatcher.s­ervice(Dispatcher.jav­a:49)

            at ja­vax.servlet.http.Http­Servlet.service(HttpS­ervlet.java:728)

            at co­m.meterware.servletun­it.InvocationContextI­mpl.service(Invocatio­nContextImpl.java:76)

            at co­m.meterware.servletun­it.ServletUnitClient.­newResponse(ServletUn­itClient.java:126)

            at co­m.meterware.httpunit.­WebClient.createRespo­nse(WebClient.java:64­7)

            at co­m.meterware.httpunit.­WebWindow.getResource­(WebWindow.java:220)

            at co­m.meterware.httpunit.­WebWindow.getSubframe­Response(WebWindow.ja­va:181)

            at co­m.meterware.httpunit.­WebWindow.getResponse­(WebWindow.java:158)

            at co­m.meterware.httpunit.­WebWindow.updateWindo­w(WebWindow.java:199)

            at co­m.meterware.httpunit.­WebWindow.getSubframe­Response(WebWindow.ja­va:183)

            at co­m.meterware.httpunit.­WebWindow.getResponse­(WebWindow.java:158)

            at co­m.meterware.httpunit.­WebClient.getResponse­(WebClient.java:122)

            at te­st.Authorization.test­AuthCorrectInput_Wron­gPassword(Authorizati­on.java:102)

            at su­n.reflect.NativeMetho­dAccessorImpl.invoke0­(Native Method)

            at su­n.reflect.NativeMetho­dAccessorImpl.invoke(­Unknown Source)

            at su­n.reflect.DelegatingM­ethodAccessorImpl.inv­oke(Unknown Source)

            at ja­va.lang.reflect.Metho­d.invoke(Unknown Sour­ce)

            at or­g.junit.runners.model­.FrameworkMethod$1.ru­nReflectiveCall(Frame­workMethod.java:45)

            at or­g.junit.internal.runn­ers.model.ReflectiveC­allable.run(Reflectiv­eCallable.java:15)

            at or­g.junit.runners.model­.FrameworkMethod.invo­keExplosively(Framewo­rkMethod.java:42)

            at or­g.junit.internal.runn­ers.statements.Invoke­Method.evaluate(Invok­eMethod.java:20)

            at or­g.junit.internal.runn­ers.statements.RunBef­ores.evaluate(RunBefo­res.java:28)

            at or­g.junit.runners.Paren­tRunner.runLeaf(Paren­tRunner.java:263)

            at or­g.junit.runners.Block­JUnit4ClassRunner.run­Child(BlockJUnit4Clas­sRunner.java:68)

            at or­g.junit.runners.Block­JUnit4ClassRunner.run­Child(BlockJUnit4Clas­sRunner.java:47)

            at or­g.junit.runners.Paren­tRunner$3.run(ParentR­unner.java:231)

            at or­g.junit.runners.Paren­tRunner$1.schedule(Pa­rentRunner.java:60)

            at or­g.junit.runners.Paren­tRunner.runChildren(P­arentRunner.java:229)

            at or­g.junit.runners.Paren­tRunner.access$000(Pa­rentRunner.java:50)

            at or­g.junit.runners.Paren­tRunner$2.evaluate(Pa­rentRunner.java:222)

            at or­g.junit.internal.runn­ers.statements.RunBef­ores.evaluate(RunBefo­res.java:28)

            at or­g.junit.internal.runn­ers.statements.RunAft­ers.evaluate(RunAfter­s.java:30)

            at or­g.junit.runners.Paren­tRunner.run(ParentRun­ner.java:300)

            at or­g.eclipse.jdt.interna­l.junit4.runner.JUnit­4TestReference.run(JU­nit4TestReference.jav­a:50)

            at or­g.eclipse.jdt.interna­l.junit.runner.TestEx­ecution.run(TestExecu­tion.java:38)

            at or­g.eclipse.jdt.interna­l.junit.runner.Remote­TestRunner.runTests(R­emoteTestRunner.java:­467)

            at or­g.eclipse.jdt.interna­l.junit.runner.Remote­TestRunner.runTests(R­emoteTestRunner.java:­683)

            at or­g.eclipse.jdt.interna­l.junit.runner.Remote­TestRunner.run(Remote­TestRunner.java:390)

            at or­g.eclipse.jdt.interna­l.junit.runner.Remote­TestRunner.main(Remot­eTestRunner.java:197)

            Caused by: javax.serv­let.ServletException:­ java.lang.AbstractMe­thodError: com.meterw­are.servletunit.Servl­etUnitServletContext.­getClassLoader()Ljava­/lang/ClassLoader;

            at or­g.apache.jasper.servl­et.JspServlet.service­(JspServlet.java:343)

            at ja­vax.servlet.http.Http­Servlet.service(HttpS­ervlet.java:728)

            at co­m.meterware.servletun­it.RequestDispatcherI­mpl.forward(RequestDi­spatcherImpl.java:54)

            at co­ntrollers.Auth.index(­Auth.java:78)

            ... 4­4 more

            Caused by: java.lang.­AbstractMethodError: ­com.meterware.servlet­unit.ServletUnitServl­etContext.getClassLoa­der()Ljava/lang/Class­Loader;

            at or­g.apache.jasper.compi­ler.TagPluginManager.­init(TagPluginManager­.java:72)

            at or­g.apache.jasper.compi­ler.TagPluginManager.­apply(TagPluginManage­r.java:56)

            at or­g.apache.jasper.compi­ler.Compiler.generate­Java(Compiler.java:24­0)

            at or­g.apache.jasper.compi­ler.Compiler.compile(­Compiler.java:373)

            at or­g.apache.jasper.compi­ler.Compiler.compile(­Compiler.java:353)

            at or­g.apache.jasper.compi­ler.Compiler.compile(­Compiler.java:340)

            at or­g.apache.jasper.JspCo­mpilationContext.comp­ile(JspCompilationCon­text.java:646)

            at or­g.apache.jasper.servl­et.JspServletWrapper.­service(JspServletWra­pper.java:357)       ­       

            at or­g.apache.jasper.servl­et.JspServlet.service­JspFile(JspServlet.ja­va:390)

            at or­g.apache.jasper.servl­et.JspServlet.service­(JspServlet.java:334)

            ... 4­7 more

The first block represents an invocation error caught by central controller (Dispatcher) servlet while invoking method in which an AbstractMethodError had been thrown. The second and third ones are about that error.

The code of the test method is as follows:

            @Test

            publi­c void testAuthIncorr­ectInput_Long() throw­s Exception {

                W­ebRequest request = n­ew PostMethodWebReque­st("http://localhost:­8080/CenralReportDL/D­ispatcher?query=auth"­);

                S­tring longString = ne­w String();

                f­or (int i = 0; i < 52­; i++) {

                 ­           longString­ += "aA_ba";

                }

            reque­st.setParameter("user­name", longString);

            reque­st.setParameter("pass­word", longString);

                W­ebResponse response =­ client.getResponse(r­equest);


                a­ssertNotNull("No resp­onse received", respo­nse);
            }

How can I get rid of this error? Is there a workaround? Should I maybe use some other means of servlet testing? Also please do not suggest framework-specific testing utils such as strutstest, I want an actual solution for bare java web application.

Simulation of common gestures in amazon device farm

I am performing testing of my application in Amazon Device Farm. I am accessing Samsung Galaxy S3, Apple iPhone 5C and Samsung galaxy Tablet devices through Remote Access in Amazon Device Farm. I require simulation of common gestures like Zoom In, Zoom Out, shake, glimp etc.. For the Zoom In and Zoom out actions, I got the following solution:enter image description here

But I am not able to find solution for other gestures. Also I haven’t found anything regarding the same . If anyone has verified common gestures in Amazon Device Farm then please provide me the ssolution for the same.

wanted to know how to load test in jmeter or any other tool to test login page with multiple logins at the same time

want to know step by step process in jmeter to test multiple users logging in at the same time . please help me with that . I am a beginner

how to test params[:view]

I want to test default view (when no view kind is given, params[:view] is empty)? How to use params[:view] in testing?

question index

<div class="well well-sm">
  <strong>Display</strong>
    <div class="btn-group">
      <%= link_to params.merge(:view => 'grid'), class: "btn btn-default btn-sm" do %>
      <%= image_tag "grid.png" ,width: "15"%> Grid <% end %>
      <%= link_to params.merge(:view => 'list'), class: "btn btn-default btn-sm"  do %> <%= image_tag "list.png" ,width: "15"%> List <% end %>
    </div>
</div><br><br><br>
<div id="entries">
  <% if params[:view] == 'grid' %>
    <%= render :partial => 'grid' %>
  <% elsif params[:view] == 'list' %>
    <%= render :partial => 'list' %>
  <%else%>
    <%= render :partial => 'list' %>
  <% end %>
</div>

class QuestionsControllerTest < ActionController::TestCase
  test "default_view" do
    u = FactoryGirl.create :question
    get :index
    assert_select params[:view].empty?
  end
end

In the terminal

 1) Error:
QuestionsControllerTest#test_default_view:
ActiveRecord::RecordInvalid: Validation failed: User can't be blank
    test/controllers/questions_controller_test.rb:11:in `block in <class:QuestionsControllerTest>'

4 runs, 6 assertions, 0 failures, 1 errors, 0 skips

Tellurium 52 - how to handle dynamically injected form element?

When I have to reference an element that exists in a DOM document I simply write

When "039f60d5-1b38-451a-b191-5e4b86273324" is selected from the "work_right_country_id" drop-down menu

and that works perfectly.

My problem is different. I have a dropdown that populates another dropdown with options that depend on a selected parent. Let's say that I have a static select / option with list of all countries. Person selects a country and that populates another dropdown with all available visas for that country. Dropdown with visas is populated via append in jQuery.

I thought that simply calling a "delay" command to Tellurium test will do the job - I will pick a country, wait 2 seconds for a population of visas by calling:

Given a test delay of 2 seconds

then:

When "4e15548c-5327-4a7e-95a2-3923d7355e2c" is selected from the "work_right_id" drop-down menu

Apparently it fails:

enter image description here

Any ideas how to call elements that are not part of a static DOM?

How do I modify my Yesod app during a test

I have a Yesod app with the type:

data App = App
    { appSettings    :: AppSettings
    , appStatic      :: Static
    , appConnPool    :: ConnectionPool
    , appHttpManager :: Manager
    , appLogger      :: Logger
    , appStripe      :: forall a. ((FromJSON (StripeReturn a)), Typeable (StripeReturn a))
                     => StripeConfig
                     -> StripeRequest a
                     -> IO (Either StripeError (StripeReturn a))
    }

and a helper function

stripe :: (FromJSON (StripeReturn a), Typeable (StripeReturn a))
       => StripeRequest a
       -> Handler (Either StripeError (StripeReturn a))
stripe req = do
  f <- appStripe <$> getYesod
  c <- appStripeConfig . appSettings <$> getYesod
  liftIO $ f c req

that is used in several handlers. (The appStripe field of the App is never referenced directly in any handlers.) In makeFoundation, everything is as scaffolded, except that the appStripe field is filled in with Web.Stripe.stripe from the stripe-haskell library.

In my tests, I would like to be able to mock the calls to Stripe, so I have the following function:

withStripeExpecting :: (FromJSON (StripeReturn a), Typeable (StripeReturn a))
                    => StripeRequest a
                    -> Either StripeError (StripeReturn a)
                    -> YesodExample App ()
                    -> YesodExample App ()
withStripeExpecting _expectedReq res = withStateT $ \yed -> yed {yedSite = f (yedSite yed)}
  where f app = app {appStripe = mock}
        mock :: Typeable (StripeReturn b)
             => StripeConfig
             -> StripeRequest b
             -> IO (Either StripeError (StripeReturn b))
        mock _ _actualReq = do
          -- assert actualReq matches expectedReq (in IO???)
          return $ case cast res of
                    Just a -> a
                    Nothing -> error "Stripe return types don’t match in mock."

which I use in test cases like:

spec :: Spec
spec = withApp $ do
  describe "create" $ do
    it "returns a 201" $ do
      -- a bunch of set-up elided
      withStripeExpecting stripeReq (Right stripeRes) $ do
        requestWithSubject "auth0|fake" $ do
          setMethod "POST"
          setUrl $ SubscriptionPlansR walletId
          setRequestBody encoded
          addRequestHeader (H.hContentType, "application/json")
        statusIs 201

which compiles and runs, but throws an error StripeError {errorType = InvalidRequest, errorMsg = "Invalid API Key provided: ", errorCode = Nothing, errorParam = Nothing, errorHTTP = Just UnAuthorized} suggesting that it is running the real stripe IO action instead of the mock.

How do I change a field of the App during a test so that it will be used by the handler under test?

failed compile from test_helper

i wrote test_helper for testing my react components but every time i hit npm start and following errors come out.

> jsonplaceholder-client@0.0.1 test /Users/WOOJUNG/Desktop/jsonplaceholder-client
> mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test

/Users/WOOJUNG/Desktop/jsonplaceholder-client/node_modules/babel-register/node_modules/babel-core/lib/transformation/file/index.js:573
      throw err;
      ^

SyntaxError: /Users/WOOJUNG/Desktop/jsonplaceholder-client/test/test_helper.js: Unexpected token (21:4)
  19 | function renderComponent(ComponentClass, props = {}, state = {}) {
  20 |   const componentInstance =  TestUtils.renderIntoDocument(
> 21 |     <Provider store={createStore(reducers, state)}>
     |     ^
  22 |       <ComponentClass {...props} />
  23 |     </Provider>
  24 |   );

it seems like error occurs because of failed compile test_helper. I'm not sure but as I know js:babel-core/register can compile es6 but it fails. should I give another options to compile test_helper? but I have no idea. T_ T

How do I delay the execution of all unit tests in XCode?

I need my unit tests to wait for our sub-systems to initialize which usually takes a few seconds. In order to wait for this, I can do the following in a test

- (void)testReverseActionWithOffset
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"High Expectations"];

    // Wait for proper initialization of Realm and CrimsonObject system...
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{

The problem is, using this technique, I have to do this wait in every single test method. This leads to there being a two second delay between each test even after the system is booted up. Because the test methods run in an undetermined order, I can't put the delay in just one method. What is the correct way to handle this under XCode?

Test with Twilio Connect App

Is there a way to test with the Twilio Connect App? You can only authorize an app that is not a free trial account by logging in which authorizes the production account. You do not get a chance to authorize a test account. Because of that any calls you try to make with the Connect App test credentials fail because your test credentials are not authorized to use the other production account. Does anyone know of any workarounds for this?

Integration tests mocking facades vs injecting mocks

We have some legacy laravel projects which use facades in the classes.

use Cache;

LegacyClass
{
    public function cacheFunctionOne()
    {
         $result = Cache::someFunction('parameter');

         // logic to manipulate result

         return $result;
    }

    public function cacheFunctionTwo()
    {
         $result = Cache::someFunction('parameter');

         // different logic to manipulate result

         return $result;
    }
}

Our more recent projects use dependency injection of the underlying laravel classes that the facades represent as has been hinted at by Taylor Otwell himself. (We use constructor injection for each class, but to keep the example short, here I use method injection and use a single class.)

use Illuminate\Cache\Repository as Cache;

ModernClass
{
    public function cacheFunctionOne(Cache $cache)
    {
         $result = $cache->someFunction('parameter');

         // logic to manipulate result

         return $result;
    }

    public function cacheFunctionTwo(Cache $cache)
    {
         $result = $cache->someFunction('parameter');

         // different logic to manipulate result

         return $result;
    }
}

I know facades can be mocked

public function testExample()
{
    Cache::shouldReceive('get')
                ->once()
                ->with('key')
                ->andReturn('value');

    $this->visit('/users')->see('value');
}

Which works nicely for unit tests. The problem I am trying to understand is if these facades are mocked 'globally'.

For example, lets imagine I am writing an integration test (testing a few interconnected classes while mocking services - not an end to end test using live services) which at some point, executes two separate classes which contain the same facade that calls the same method with the same parameters.

In between these classes being called, is some complex functionality that changes what data is returned by that facades method using the same parameter.*

$modernClass->cacheFunctionOne($cache); // easily mocked

// logic that changes data returned by laravel Cache object function 'someFunction'

$modernClass->cacheFunctionTwo($cache); // easily mocked with a different mock

Our modern classes are easy to test because the underlying class that the facade represents is injected into each class (in this example, each method). This means I can create two separate mocks and inject them into each class (method) to mock the different results.

$legacyClass->cacheFunctionOne();

// logic that changes data returned by laravel Cache object function 'someFunction'

$legacyClass->cacheFunctionTwo();

In the legacy systems though, it would seem that the mocked facade is 'global' so that when the facade is run in each class, the exact same value is returned.

Am I correct in thinking this?

*I understand this example may seem completely redundant from a code architecture and testing point of view, but I am stripping out all real functionality to try and give some sort of 'simple' example of what I am asking.

Check which Intent open Espresso

Whether it is possible to trace which the Activiti opened after pressing the button?
I have a test, after clicking on the button sends a request to the server, and as long as they are sent, opens Activiti to the successful execution of the test to check what is open Activiti
Example of my test:

 private void startTest() {
    recreateAuthData(InstrumentationRegistry.getTargetContext(), "d78269d9-9e00-4b8d-9242-815204b0a2f6", "3f32da21-914d-4adc-b6a1-891b842a2972");

    InstrumentationRegistry.getTargetContext().getSharedPreferences(ActivitySplashScreen.class.getSimpleName(),
            Context.MODE_PRIVATE).edit().putInt(ActivitySplashScreen.PROPERTY_APP_VERSION, ActivitySplashScreen.getAppVersion(InstrumentationRegistry.getTargetContext())).commit();
    InstrumentationRegistry.getTargetContext().getSharedPreferences(ActivitySplashScreen.class.getSimpleName(),
            Context.MODE_PRIVATE).edit().putString(ActivitySplashScreen.PROPERTY_REG_ID, "testKey").commit();

    mActivityRule.launchActivity(setIntent());
    // inputPinCode("2794");
}

@Test
public void testIdent() {
    startTest();
    onView(withText("ПРО")).perform(click());
    putDelay(500);
    onView(withId(R.id.get_pro)).perform(click());
    onView(withText("Авторизация по паспортным данным")).perform(click());
    putDelay(500);
    closeSoftKeyboard();
    onView(withId(R.id.btn_goto_passport)).perform(click());
    onView(withHint("Серия и номер паспорта")).perform(replaceText("9894657891"));
    onView(withHint("Дата выдачи паспорта")).perform(replaceText("17032014"));
    onView(withHint("Дата рождения")).perform(replaceText("31091994"));
    onView(withHint("СНИЛС")).perform(replaceText("54665285919"));
    putDelay(500);
    Log.d("TestWidget", hasComponent(hasShortClassName("ActivityMain")).toString());
    onView(withId(R.id.btn_next)).perform(click());
    // some code which check which activity is display now
    putDelay(500);

}

Angular 2 Jasmine test failed - sync emitter used

I have angular 2 component - list, that contains items. It is filterable and supports 2 events: filtering - before the filter process happens; filtered - after the filter process happens. Here is the implementation:

 @Output() filtering = new EventEmitter(false); // synchronous event emitter
 @Output() filtered = new EventEmitter(); // async event emitter

filter() {
            filteringArgs = { cancel: false };

            this.filtering.emit(filteringArgs);
            
            // Because the emitter is synchronous, the filtering handler will be executed now
            // and then the execution of filter function will continue from here
            
            if(filteringArgs.cancel) { 
                return; 
            }            

            // Filtering is happens here

            var result = { /* result of filtering */ };

            filteredArgs = { result: result }
            this.filtered.emit(filteredArgs);             
    }

When I use the following handler:

filteringHandler(args) { args.cancel = true; }

in its parent component to cancel the filtering process - it works as it is expected: no filter happens. So I want to test it and wrote the following test:

it('should cancel emitted filter events',
    async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
      var template = '<list (filtering)="filteringHandler($event)"><list-item>Item 1</list-item><list-item>Item 2</list-item><list-item>Item 3</list-item></list>';
                return tcb.overrideTemplate(ListTestComponent, template)
                .createAsync(ListTestComponent)
                .then((fixture) => {
                      var items, visibleItems,
                          list = fixture.componentInstance.viewChild;

                      spyOn(list.filtering, 'emit');
                      spyOn(list.filtered, 'emit');

                      fixture.detectChanges();
                      items = list.items;                      
                      visibleItems = items.filter((listItem) => { return !listItem.hidden; });
                      expect(list.items.length).toBe(3);
                      expect(visibleItems.length).toBe(3);
                      
                      list.searchInputElement = document.createElement('input');                      
                      list.searchInputElement.value = "3"; // filtering down only to item 3
                      fixture.componentInstance.filteringHandler = (args: any) => { args.cancel = true; }; // it should prevent form filtering
                      fixture.detectChanges(); 
                      list.filter(); // filter should not happen because of canceling
                      fixture.detectChanges();        

                      visibleItems = items.filter((listItem) => { return !listItem.hidden; }); 
                      expect(visibleItems.length).toBe(3);
                      expect(list.filtering.emit).toHaveBeenCalledWith({ cancel: false });
                      expect(list.filtered.emit).not.toHaveBeenCalledWith({ result: [visibleItems[0]] });
                }).catch (reason => {
                    console.log(reason);
                    return Promise.reject(reason);
                });
         })));

However, despite the fact that I expect from test to cancel the filtering, it does not and filter happens. Which leads to unexpected result for the test and it fails. What is wrong with testing of sync emitter using karma/jasmine?

API Testing framework

I am looking for a way to test our APIs. Our APIs are C# MVC but all our front end tests are in Jasmine / Karma and ran from Gulp / Node.

Ideally any solution we come up with would use Jasmine / Karma or be fairly similar. It would also ideally be on the simpler side to write as I was hoping a test engineer would be able to write and maintain these tests.

Is there anything better to use than Jasmine and Karma? One problem I can foresee is that sometimes we'll want to test our production APIs, sometimes our local (staging) ones. The point being that the endpoint will likely change but the machine running the tests may not, which may incur CORS issues if being done using javascript / web browser.

Can anyone offer some advice?

How to run all the webtests from commandline

I have dll file for webtests. I used the below command to execute all my webtests

mstest /testcontainer:"MyPath\PostAccessToken.dll" /resultsfile:MyResultPath\MyResults.trx

When i tried the above command I got the below message.

Microsoft (R) Test Execution Command Line Tool Version 12.0.21005.1 Copyright (c) Microsoft Corporation. All rights reserved.

Loading PostAccessToken.dll... Starting execution... No tests to execute.

My dll file contents are

[assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName=".NET Framework 4.5")]
[assembly: AssemblyTitle("PostAccessToken")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PostAccessToken")]
[assembly: AssemblyCopyright("Copyright \x00a9  2016")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("2227ff72-2254-4e3e-af43-76a98b558c80")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.EnableEditAndContinue | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.Default)]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows=true)]

how can I run all webtests from this library by one command?

Angular 2 - Http-Testing - Error: "Cannot read property 'getCookie' of null"

Always get this error in console, when running Jasmine Tests with karma on the following code:

Error:

TypeError: Cannot read property 'getCookie' of null

Service:

//http.service.ts
import {Injectable, Inject, ReflectiveInjector}    from '@angular/core';
import {Headers, Http, Response, HTTP_PROVIDERS} from '@angular/http';

import {Observable} from "rxjs";

const injector = ReflectiveInjector.resolveAndCreate(HTTP_PROVIDERS);
const http = injector.get(Http);

@Injectable()
export class HttpService {

  constructor() {}

  httpTest(){
    return http.get("http://ift.tt/2bIH98B")
        .map(response =>{ return response.json()});
  }
}

Testfile:

//http.service.spec.ts
import {
  it,
  describe,
  expect,
  inject,
  addProviders,
  beforeEach
} from '@angular/core/testing';
import {MockBackend, MockConnection} from '@angular/http/testing';
import {provide} from '@angular/core';
import {
  Http,
  BaseRequestOptions,
  Response,
  ResponseOptions
} from '@angular/http';


import { HttpService } from './http.service';

describe('Http-Test', () => {

  beforeEach(() => {
    addProviders([
      HttpService,
      BaseRequestOptions,
      MockBackend,
      {
        provide: Http,
        useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
          return new Http(backend, defaultOptions);
        },
        deps: [MockBackend, BaseRequestOptions]
      }
    ])
  });

  beforeEach(inject([MockBackend], (backend: MockBackend) => {
    const baseResponse = new Response(new ResponseOptions({ body: 'userListAsJSON' }));
    backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse));
  }));

  it('should return response when subscribed to httpTest',
    inject([HttpService], (testService: HttpService) => {
      testService.httpTest().subscribe((res: Response) => {
        expect(res.text()).toBe('userListAsJSON');
      });
    })
  );

})

Didn't finde anything why it can't "read property 'getCookie' of null", or why it tries to read it at all...

Functional testing: How to keep backend mock up to date

For running functional tests against a frontent, we consider mocking our backend. Our BE iterates quite fast and changes a lot, though. So mocking it would mean we'd always need to be aware of all changes and update our mocks accordingly.

I was wondering if it is possible to automate this process.

Urbancode deploy with IBM CLM RQM

I created a test suite on IBM CLM - RQM and and an RQM adapter is installed to run the test cases on remote machine.

I am executing RQM test suite from UrbanCode process. This integration is working file.

I want to print a link of IBM RQM execution record in IBM Urbancode so that user can navigate from Urbancode to RQM with single click and see the detailed status of test suite on RQM.

Is it possible to get the RQM test suite execution status link and log it on Urbancode deploy?

mardi 30 août 2016

How to trigger window resize event using vanilla javascript?

I'm trying to trigger resize event using plain js for testing purpose, but window.resizeTo() and window.resizeBy() don't trigger the event according to the modern browsers prevent these actions. I tried jquery $(window).trigger('resize'); but it works only for events that attached via jquery like $(window).on('resize', handler);. however in my case the project I am working on uses plain javascript.

example

window.addEventListener('resize', function(){
    console.log('window has been resized !');
});

// or even using global onresize
window.onresize = function() {
    console.log('window has been resized!');
};

Ist is possible to run regression with webdriver?

For each test i have created a java class. now i am wondering how to run all these test once. I mean how to execute regression test and see result in Web-driver.
Is it possible in Web-driver?
Thanks

jenkins chromediver protactor issues

I am curently working in an angularjs project and I build tests with protractor. I would like to automate my tests with Jenkins. I wrote a little shell script to launch my tests and it works well from my terminal. But I have an issue when I try to launch the script from Jenkins. In the jenkins console I can see this error message :

Started by user anonymous
Building in workspace /var/lib/jenkins/workspace/test
[WS-CLEANUP] Deleting project workspace...
[WS-CLEANUP] Done
[test] $ /bin/sh -xe /tmp/hudson2254278298273314957.sh
+ sh /home/test/Desktop/jenkins.sh
[4mRunning "connect:server" (connect) task[24m
[4mRunning "protractor:chrome" (protractor) task[24m
Waiting forever...
Started connect web server on http://localhost:3001
Using ChromeDriver directly...
[launcher] Running 1 instances of WebDriver

waiting... 10 seconds

/home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/lib/atoms/error.js:108
      var template = new Error(this.message);
                     ^
    UnknownError: unknown error: Chrome failed to start: exited abnormally
      (Driver info: chromedriver=2.23.409687 (c46e862757edc04c06b1bd88724d15a5807b84d1),platform=Linux 4.4.0-21-generic x86_64)
        at new bot.Error (/home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/lib/atoms/error.js:108:18)
        at Object.bot.response.checkResponse (/home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/lib/atoms/response.js:109:9)
        at /home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:160:24
        at [object Object].promise.ControlFlow.runInFrame_ (/home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/lib/goog/../webdriver/promise.js:1857:20)
        at [object Object].goog.defineClass.notify (/home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/lib/goog/../webdriver/promise.js:2448:25)
        at [object Object].promise.Promise.notify_ (/home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/lib/goog/../webdriver/promise.js:564:12)
        at Array.forEach (native)
        at [object Object].promise.Promise.notifyAll_ (/home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/lib/goog/../webdriver/promise.js:553:15)
        at goog.async.run.processWorkQueue (/home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/lib/goog/async/run.js:130:15)
        at process._tickCallback (node.js:368:9)
    From: Task: WebDriver.createSession()
        at Function.webdriver.WebDriver.acquireSession_ (/home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:157:22)
        at Function.webdriver.WebDriver.createSession (/home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:131:30)
        at new Driver (/home/test/workspace/frontend/node_modules/protractor/node_modules/selenium-webdriver/chrome.js:810:36)
        at [object Object].DirectDriverProvider.getNewDriver (/home/test/workspace/frontend/node_modules/protractor/lib/driverProviders/direct.js:68:16)
        at [object Object].Runner.createBrowser (/home/test/workspace/frontend/node_modules/protractor/lib/runner.js:182:37)
        at /home/test/workspace/frontend/node_modules/protractor/lib/runner.js:263:21
        at _fulfilled (/home/test/workspace/frontend/node_modules/protractor/node_modules/q/q.js:797:54)
        at self.promiseDispatch.done (/home/test/workspace/frontend/node_modules/protractor/node_modules/q/q.js:826:30)
        at Promise.promise.promiseDispatch (/home/test/workspace/frontend/node_modules/protractor/node_modules/q/q.js:759:13)
        at /home/test/workspace/frontend/node_modules/protractor/node_modules/q/q.js:525:49
        at flush (/home/test/workspace/frontend/node_modules/protractor/node_modules/q/q.js:108:17)
        at nextTickCallbackWith0Args (node.js:419:9)
        at process._tickCallback (node.js:348:13)
        at Function.Module.runMain (module.js:444:11)
        at startup (node.js:136:18)
        at node.js:966:3
    [launcher] Process exited with error code 1
    [31m>> [39m
    [33mWarning: Tests failed, protractor exited with code: 1 [4mUsed --force, continuing.[24m[39m

    [31mDone, but with warnings.[39m
    Process leaked file descriptors. See http://ift.tt/1k6kBQ6 for more information
    Finished: SUCCESS

I am completely blocked because of this problem. Do you have any clue to solve this issue? Thank y'all!

how to test setter and getter?

how to test setters and getters?

function someClass(){
   var data;

   this.setData = function(value){
       // some complex logic
   }

   this.getData = function(){
      // some complex logic
   }
}

is it right way for execute setData and getData for test it bouts in one test case?

Automated testing in web applications

We are developing a very large web application using C# and JavaScript. The majority of our calls in the code are handled with JavaScript on the front-end and the only real back-end work is the SQL server which retrieves the relevant dataset and returns it as a JSON object which is then handled once again with JavaScript.

We are currently doing all testing manually with our testers who verify the page functionality against the design specifications to make sure the software is working as expected.

I would love to be able to add some automated testing to the application. I've looked into Unit Testing and it seems that it works a lot better if you have a lot of C# methods with inputs and outputs which are easy to trace and verify that they are working.

What are the standard methods in use in the industry which we can use to verify that the whole application (or at least a majority of it) is working properly?

The sort of things I want to check are:

  1. We have an input page which lets you create a user. This input page should update, let's say, 5 tables in the database. I am adding 10 different pages which allow me to create users in the application, how can I verify that all of those pages are inserting correctly and working properly?

  2. I have a page where I can click a button which inserts a row into the database. How can I check that it's outputting correctly in all the different places it should output?

Off the top of my head, I cannot think of all the different cases I need to check but there are a huge number of them. As far as I have understood, any visual errors can only be tested by users who are manually testing.

I am looking for some feedback on what the best methods are and also how they can be applied to our type of application.

Testing SIP over WAN using sipp ... audio transmission

I looked at Playing audio file using sipp prior to posting this... I followed the instructions posted there. However, looking at a packet capture I see that typically my calls only contain 8-12 packets - not nearly enough to transfer 30s of audio that I created in my .WAV file. Additionally, wireshark doesn't detect anything other than SIP traffic - no RTP payloads.

Only the server side I see "Aborting call on UDP retransmission timout for Call-ID 'xxx..." I don't see any errors on the client side logs.

Are there any updated examples of how to push an audio file to sipp acting in uas mode from sipp acting in uac mode? I've played around with it for a couple of days and read the documentation at http://ift.tt/2c8gEcz but I haven't had much luck.

Can someone point me to a howto or example scenario file for both client and server? I would love to see something using rtp_echo to send played audio back to the client in order to simulate full dialogue.

Test problems in Choco

Did someone do some testing in Choco 4.0.0 before? Could you please give me the source code of some classic CSP like n-queen, knight or hanoi? Thanks a lot.

Multiple values from same txt file

I've been using this script to load values separated by new line from files to send requests with different values.

def size 
File valueFile = new File("C:\\values\\myValueFile.txt")
File valueFile2 = new File("C:\\values\\myValueFile2.txt")
List lines = valueFile.readLines()
List lines2 = valueFile2.readLines()
size = lines.size.toInteger()
def myProps = testRunner.testCase.getTestStepByName("MyProperties") 

for( counter in 0..size-1) 
{
tempValue = lines[counter]
tempValue2 = lines2[counter]
myProps.setPropertyValue("Value", tempValue)
myProps.setPropertyValue("Value2", tempValue2)
log.info tempValue
log.info tempValue2
testRunner.runTestStepByName("updateBusinessTrip")
}

How to make it load values from same file separated by ";"? txt file would look like that:

Value1;Value2
Value1.1;Value2.1
Value1.2;Value2.2

my code is not working properly?

here is my code. WebDriverWait wait = new WebDriverWait(driver, 10); Alert alert = wait.until(ExpectedConditions.alertIsPresent());

       //Accepting alert.
       alert.accept();
       System.out.println("Accepted the alert successfully.");
    }catch(Throwable e){
       System.err.println("Error came while waiting for the alert popup. "+e.getMessage());
    }

error showing like: Error came while waiting for the alert popup. Expected condition failed: waiting for alert to be present (tried for 10 second(s) with 500 MILLISECONDS interval)

How to test the UI of a layout without attaching it to Activity in Espresso?

I am working on a app where I need to test the layout using Espresso. The problem is that its and orphaned layout without any attachments to activity or fragment (I will attach it later). I would like to test the layout without any interaction of activity or fragments.

For example I have MainActivity with activity_main.xml as its content layout. I also have another layout say "activity_details.xml". I would like to test activity_details which is not attached to any Activity at the moment.

Also it would be great if I can know how to add mock values to the layout.

Scala Play test can't find WSClient during dependency injection

I'm trying to DI a class into a Unit Test, using the following:

val injector = new GuiceInjectorBuilder().injector()
val secured = injector.instanceOf[Secured]

However when I try and run it, I get the following error:

[info] Exception encountered when attempting to run a suite with class name: org.scalatest.DeferredAbortedSuite *** ABORTED ***
[info]   com.google.inject.ConfigurationException: Guice configuration errors:
[info] 
[info] 1) No implementation for play.api.libs.ws.WSClient was bound.
[info]   while locating play.api.libs.ws.WSClient
[info]     for parameter 3 at com.fredley.Secured.<init>(Secured.scala:36)
[info]   while locating com.fredley.Secured

...

What am I doing wrong?

Android - Espresso testing - How to take a screenshot, which is shown on Testdroid?

I'm using the Espresso-framework for my Android testing and additionally I'm using the Testdroid-Cloud for automatic testing on real devices.

Does anybody know, how to tell Espresso to make a screenshot, which is shown on the Testdroid Dashboard?

If I disable Espresso, the Testdroid crawler automatically make screenshots. By suing the Espresso-framework it doesn't! See screenshot:

enter image description here

Reliable way to provoke Segmentation Fault in PHP for testing?

Is there a reliable (i.e. reproducable in any version) way to provoke a segmentation fault in PHP? I want to test how they are handled.

I'm happy with solutions specific to PHP 7.x or PHP 5.x but would prefer not to rely on known bugs that might be solved in the next release.

Difference between Scalibility Testing And Capacity Testing?

Is belong to non-functional testing type. but get confuse between these 2 types of testing.

Spock: How to use test data with @Stepwise

I used @Stepwise for automation. 8 test methods are running sequentially to complete the process. One of the methods take parameter and I want to pass multiple combinations of parameters to the method.

But the problem happening is: For the first set of parameter, the variables are populated with those parameters and processed AND instead of proceeding to the next method, the next set of parameter is populated instantly.

The source looks like:

@Stepwise
class AOSearchPageTest extends GebReportingSpec
{
    def "first_method"()
    {
    }

    def "second_method"()
    {
        when:
        at particularPage
        then:
        process(area)
        process(coutntry)
        process(airport)
        process(dest_area)
        process(dest_coutntry)
        process(dest_airport)

        where:
        area << ["アジア","ヨーロッパ"]
        country << ["日本","イギリス"]
        port << ["東京(成田・羽田)","ロンドン"]
        dest_area << ["アジア","ヨーロッパ"]
        dest_country << ["韓国","イタリア"]
        dest_port << ["ソウル","フィレンツェ"]
    }

    def "third_method"()
    {
        //Some other processing
    }

The second method first populate with the "アジア","日本","東京(成田・羽田)","アジア","韓国","ソウル" and then instantly populates with the second set.

How I can process each data set with complete life-cycle?

lundi 29 août 2016

Getting error "java.lang.NoClassDefFoundError: com/gargoylesoftware/htmlunit/html/HtmlElement"

I am using selenium webdriver for the testing I have written code:

import java.util.concurrent.TimeUnit;

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.firefox.MarionetteDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
//import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
//import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class sample_google
{

        WebDriver driver;


    @BeforeTest

    public  void setUp(){

       // FirefoxProfile profile = new FirefoxProfile();
        //System.setProperty("webdriver.gecko.driver", "D:\\ashwini\\geckodriver.exe");
        
//                driver= new MarionetteDriver();
         driver = new HtmlUnitDriver();

            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }


    @Test

    public void testLoadingFirstPage() throws Exception{

        driver.get("https://www.google.com/");
        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys("fast cars");
        searchBox.submit();
        System.out.println("Page title : " + driver.getTitle());
        WebElement resultCount = driver.findElement(By.id("resultStats"));
        System.out.println("Result Count : " + resultCount.getText());
       

    }
    @AfterTest
          public void teardown()
          {
                  //driver.quit();
          }

    
}
However I am getting output
FAILED CONFIGURATION: @BeforeTest setUp
java.lang.NoClassDefFoundError: com/gargoylesoftware/htmlunit/html/HtmlElement
        at sample_google.setUp(sample_google.java:31)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
        at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:514)
        at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:215)
        at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
        at org.testng.TestRunner.beforeRun(TestRunner.java:656)
        at org.testng.TestRunner.run(TestRunner.java:624)
        at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
        at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
        at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
        at org.testng.SuiteRunner.run(SuiteRunner.java:268)
        at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
        at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
        at org.testng.TestNG.runSuitesSequentially(TestNG.java:1244)
        at org.testng.TestNG.runSuitesLocally(TestNG.java:1169)
        at org.testng.TestNG.run(TestNG.java:1064)
        at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:126)
        at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:152)
        at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:57)
Caused by: java.lang.ClassNotFoundException: com.gargoylesoftware.htmlunit.html.HtmlElement
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 23 more

SKIPPED CONFIGURATION: @AfterTest teardown
SKIPPED: testLoadingFirstPage

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 1
    Configuration Failures: 1, Skips: 1
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 1
===============================================

[TestNG] Time taken by org.testng.reporters.jq.Main@2752f6e2: 142 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 28 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@6e8dacdf: 14 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@2d209079: 48 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@43a25848: 15 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@b684286: 9 ms

I have included the jar of selenium-htmlunit-driver-2.46.0.jar in the code. Still getting the error. So please check what is the issue.

Thanks in advance

error in alert handling in selenium

Does any know this answer? i have tried to solve it, but i could'nt find? could you help me to find? actually i am trying to automate a user browser login page. but there is a alert box available so i want to click ok in alert box . how it is possible? error in code

protected Alert getAlert(long wait) throws InterruptedException
    {
        WebDriverWait waitTime = new WebDriverWait(driver, wait);

        try
        {
            synchronized(waitTime)
            {
                Alert alert = driver.switchTo().alert();
                // if present consume the alert
                alert.accept();

                return alert;
            }

        }
        catch (NoAlertPresentException ex)
        {
            // Alert not present
            return null;
        }

    }

Best automation tools that cover application working on PDA with Windows CE

There is one application which has developed for PDA device working with Windows CE Can anyone advise me on test automation tools that cover application working on PDA with Windows CE and mobileapplication too ? I have TestQuest in mind

React JSPM testing framework

What is the best testing framework and its associated helper libraries to use for a project in React and JSPM? I'm looking for various libraries combined together and what is specific to that set which makes it a powerful toolset? (Looking to incorporate redux later on)

clojure test for infinite loop

I want to write a test (using clojure.test) that verifies that some sample code does not cause an infinite loop. If the code that I'm testing is buggy and does cause an infinite loop, I want the test harness to report failure -- rather than just going off and looping forever. (I'm assuming a kind of infinite loop that does not overflow the stack.)

Any ideas how to do this?

What is the easest way to test that Ruby on Rails start open file

I need to test that browser open start open/save file window after the test click_on button, I prefer to do it with capybara, but cucumber or other tool fine as well.

Line numbers from HUnit-Plus / Distribution.TestSuite / stack test failures?

I'm using HUnit-Plus via stack test, which I believe makes use of Distribution.TestSuite.

When I get compilation errors, I get file paths and line numbers in the error. This is great because I can just click on the error in my editor and jump straight to the relevant code.

Other times there is no compilation error and instead I get output like this:

### Failure in testFoo: expected: 8

This isn't so great, because every time I have to navigate to the relevant test by hand.

Is there a way to get this setup to print line numbers and file paths for test failures?

Redline 13 Plugin Load Test Error

I used redline 13 to record my load test with firefox. However, at the end I got this error code.

{"request":"HTTP GET /_ylt=A0LEVi8_Mb9Xe4gAmRMnnIlQ;_ylu=X3oDMTE0MTJtMWwwBGNvbG8DYmYxBHBvcwMxBHZ0aWQDRkZVSTNDMV8xBHNlYwNzcg--/RV=2/RE=1472176575/RO=10/RU=https%3a%2f%2fwww.redline13.com%2fblog%2f2016%2f06%2fsetup-use-selenium-jmeter-firefox-plugin%2f/RK=0/RS=Gg.jR9Z1Vs_FWc1iJZrw4BQrscI-","code":410,"response":"Gone","error":""}

Acceptance test to find specific record is giving error

I'm running an acceptance test for a route, in order to find a record, but I'm getting this 2 errors on the console:

route-handler.js: Mirage: Your handler for the url /rooms/1 threw an error: Cannot read property 'find' of undefined TypeError: Cannot read property 'find' of undefined

ember.debug.js: Error while processing route: rooms.room.activity Cannot read property '_internalModel' of undefined TypeError: Cannot read property '_internalModel' of undefined

This is my acceptance test:

test('Show specific room', (assert) => {
  visit('/rooms/1/activity');
  andThen(() => {
     assert.equal( find('h1:contains(Title 1)').length, 1 );
  });
});

This is my route:

 import Ember from 'ember';

    export default Ember.Route.extend({
        model(params) {
            return this.store.findRecord('room', params.id);
        }
    });

Actually, if I do a test to verify that when visiting a route, that's the current URL, I get the same error. Could someone suggest me what could be happening or other way to solve this test?. Thanks

How can I test an event triggered by a date in the future in specs2

I would like to test the behavior of a function that has different behaviors depending on which it is being executed, is there a way to define/simulate the date in specs2?

Example how would I test the following?

def dateDependingFunction:Boolean = currentDate > aSetDate

I would like to be able to write something like

"My Date depending functions" should{
// here somehow set a date fulfilling `currentDate > aSetDate`
 "return true" in {
    dateDependingFunction:Boolean must beBeEqualTo(true)
 }

 // here somehow set a date fulfilling `currentDate < aSetDate`
 "return false" in {
    dateDependingFunction:Boolean must beBeEqualTo(false)
 }
}

Testing EditText errors with Espresso on Android

I want to test if an EditText field has an error (set with editText.setError("Cannot be blank!")).

EditText field with error

I've created an Espresso test case with the new AndroidStudio 2.2 feature, to record Espresso tests. So the code is pretty much auto-generated. But for now it only checks if the editText is displayed.

@RunWith(AndroidJUnit4.class)
public class CreateNoteActivityTitleCannotBeBlank {

    @Rule
    public ActivityTestRule<CreateNoteActivity> mActivityTestRule = new ActivityTestRule<>(CreateNoteActivity.class);

    @Test
    public void createNoteActivityTitleCannotBeBlank() {
        ViewInteraction floatingActionButton = onView(
                allOf(withId(R.id.fab_add_note),
                        withParent(allOf(withId(R.id.activity_create_note),
                                withParent(withId(android.R.id.content)))),
                        isDisplayed()));
        floatingActionButton.perform(click());

        ViewInteraction editText = onView(
                allOf(withId(R.id.tiet_note_title),
                        childAtPosition(
                                childAtPosition(
                                        withId(R.id.til_title),
                                        0),
                                0),
                        isDisplayed()));
        editText.check(matches(isDisplayed()));

    }

    private static Matcher<View> childAtPosition(
            final Matcher<View> parentMatcher, final int position) {

        return new TypeSafeMatcher<View>() {
            @Override
            public void describeTo(Description description) {
                description.appendText("Child at position " + position + " in parent ");
                parentMatcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                ViewParent parent = view.getParent();
                return parent instanceof ViewGroup && parentMatcher.matches(parent)
                        && view.equals(((ViewGroup) parent).getChildAt(position));
            }
        };
    }
}

Is there a way to test if the error is displayed?

How to create functional test for Ruby on Rails

What is the best way create tests that include:

  • set checkbox
  • bush buttom
  • etc.

for Ruby on Rails test environment?

How to click on alert message using nightwatch.js?

I use nodejs + nightwatch + chrome driver to run my e2e tests and got problem: i can't accept alert massage on page. In documentation for nightwatch i see information for Selenium Protocol to do this. But, when i try something like this:

request.post('/session/'+session+'/accept_alert', function (error, response, body) {
    console.log(error)
})

I get error:

[Error: Invalid URI "/session/9bb486d4-5e30-40bb-a236-b6921dd0f583/accept_alert"]

Can i accept alert from nightwatch? Or why i get this err? How to fix?

how to run nodeunit tests with reports on Jenkins

Im trying to find a way to run nodeunit tests on Jenkins and sow the results. up until now ive only found how to do it with mocha and other framework and not with nodeunit. is there a plugin or jenkins or something that i should do ?

Thanks

dimanche 28 août 2016

Test Automation using Node.js

My client has a new system in development using node.js.

I need to write automation scripts for the system and my client has recommended me to go with node.js this time so the developers can also take part in creation of Automation scripts.

I need recommendation for Test Automation frameworks that I could use. I have experience working with Selenium WebDriver using Java.

Any guidance and direction would be very helpful.

Thanks.

I am getting error "java.lang.NullPointerException"

I am using selenium Webdriver for the testing web application. I am using marioette driver for the same as I am havin firefox 48.0 since yusing the same the web page gets open however I am not able to put the values in the text box it gives the error " java.lang.NullPointerException" I have written code

@BeforeTest
          public void setUp() throws Exception {
                 System.setProperty("webdriver.gecko.driver", "D:\\ashwini\\geckodriver.exe");
        
                  driver= new MarionetteDriver();

            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
          }

@Test
          public void testAddAccount() throws Exception {
            driver.get("http://ift.tt/2btTiz8");
            
            driver.findElement(By.id("username")).clear();
            driver.findElement(By.id("username")).sendKeys("cp_admin");
}


@AfterTest
          public void teardown()
          {
                  driver.quit();
          }



Output is: 


1472448949884   Marionette      INFO    sendAsync 3744f8a9-772e-42fe-8c85-6f9964888fb1
FAILED: testAddAccount
java.lang.NullPointerException
        at Add_Account.testAddAccount(Add_Account.java:36)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)

real time project testing process

i want to know about the real time project manual testing process. what is the actual process of manual testing? what is the actual selenium process? i want to know how i apply the types and techniqus in manual testing? i got a reply a person who told me in testing there is a 1000 types and techiques are there in testing ? is it ? i want to know about the real time project manual testing process. what is the actual process of manual testing? what is the actual selenium process? i want to know how i apply the types and techniqus in manual testing? i got a reply a person who told me in testing there is a 1000 types and techiques are there in testing ? is it ?

How can access vistors to the wordpress admin area

I want to access my visitors to the admin area to test my theme before purchase. is there any way to do it?

Just like "wpbakery visual composer" http://ift.tt/2bKHJED

Thanks in advance

How to write a unit test case for a private static method using Fakes assembly (Shims) c#

I've created shims correctly for both my public and private methods and I can test public static method. My question is how do I test a static PRIVATE method using a shim? I can create the delegate but then what do Id o after that? Please explain using an example.

Mockito exception when Espresso added to project

I was successfully using Mockito in my project, then I decided to add some Espresso testing (As described here:http://ift.tt/2bKskRH) and I am stuck - when I add espresso to my build.gradle and I get problems with Mockito.

My dependencies in build.gradle when Mockito is working OK, e.g. my tests which use Mockito pass:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.4.0'
    testCompile 'junit:junit:4.12'
    //Mockito framework
    testCompile 'org.mockito:mockito-core:1.10.19'
    // http://ift.tt/2bSacZx
    testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '1.6.4'
    testCompile 'org.powermock:powermock-api-mockito:1.5.5'
    androidTestCompile ('com.android.support:support-annotations:23.4.0')
    //androidTestCompile ('com.android.support.test.espresso:espresso-core:2.2.2')
}

When I uncomment the last line to include com.android.support.test.espresso:espresso-core:2.2.2 and I run my tests again I get the following error for some of them:

java.lang.IllegalAccessError: class org.mockito.internal.creation.jmock.ClassImposterizer$1 cannot access its superclass org.mockito.internal.creation.cglib.MockitoNamingPolicy

    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at org.mockito.internal.creation.jmock.ClassImposterizer.<clinit>(ClassImposterizer.java:38)
    at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23)
    at org.powermock.api.mockito.internal.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:43)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
    at org.mockito.Mockito.spy(Mockito.java:1368)
    at todolistj.todolist.unittest.CustomClass.size(CustomClass.java:54)

All the tests that fail are failing either on Mockito.spy or on Mockito.mock methods. Something like:

CustomClass1 li1 = Mockito.spy(new CustomClass1(somevar));

or

View vm= Mockito.mock(View.class);

Any help would be appreciated!

Override controller test scaffold for rails 5

I tried to override the controller test generator for scaffolding in rails 5. I found the original file, but can't place it in the template directory.

If I read correctly this post Changing scaffold-controller-generator-templates in Rails, the path should be :

lib/templates/rails/test_unit/controller.rb 

or

lib/templates/rails/test_unit/functional_test.rb # from the scaffold sources

Finally I tested lots of combinaisons of directories and files names, but none work.

Does anybody know how to do that ?

Can UI Automation Scripts that work in IE11 be used in Edge?

This is Praveen and I would like know whether we can reuse the existing Coded UI Automation Scripts for Microsoft Egde browser.

We have written coded ui tests for automation using visual studio 2015 and we are running them on IE11 browser without any issues. I would like know whether we can reuse the same coded ui scripts without rewriting the code for running tests using Microsoft edge browser.

Thank you so much in advance.

Laravel test actingAs

i am trying to test one form of my website. This form is available only for logged in users. With the following code i get a failure. The html code which is returned is of the login page, so somehow the actingAs() method seems not to work ?

class AnalysesTest extends TestCase {

use DatabaseTransactions;

public function testSeeAddAnalysesForm()
{
    $pass = 'mypass';
    $user = $this->create_fake_user($pass);
    $this->actingAs($user)
    ->visit('analyses/create')
    ->see('Save');
}

protected function create_fake_user($pass) {
    $faker = Faker\Factory::create();
    return App\Models\User::create([
        'name' => $faker->name,
        'company' => $faker->name,
        'position' => 'Assistant',
        'email' => $faker->email,
        'phone' => $faker->phoneNumber,
        'status' => 1,
        'password' => $pass,
    ]);
}

}

The error I get is: Failed asserting that the page contains the HTML [Save]. Please check the content above.

Unable to use @DataJpaTest if Spring security is on classpath

I am trying to update my test cases to use the @DataJpaTest. However, I am encountering some issues that appear to be related to Spring Security. The following is an example of the test class.

@RunWith(SpringRunner.class)
@DataJpaTest
public class ExampleRepositoryTest  {

    @Rule
    public final ExpectedException exception = ExpectedException.none();

    @Inject
    private ExampleRepository repository;

    @Test
    public void test() throws Exception {
       ...
    }

I keep getting the error java.lang.IllegalStateException: Failed to load ApplicationContext due to the missing bean org.springframework.security.config.annotation.ObjectPostProcessor.

The project is a RESTful application with Spring security. The original test case created a full Spring Boot context using @SpringBootTest. The @DataJpaTest is supposed to help me test the JPA slice, which is exactly what I want.

Any help would be greatly appreciated. What am I missing?

Are There Limitations On Apple's Test Users When Testing Renewable Subscriptions?

Not really a programming question as such but I was hoping that someone might no the answer. I'm integrating an Auto Renewable subscription system using MKStoreKit and I'm currently testing the monthly subscription. Now i've noticed that Apple test users seem to renew every 5 minutes up to 5 times.

After that I can renew again but the automatic renewal process seems to stop and does not auto renew. Is this an Apple feature? I'm wondering if I've made a mistake whilst integrating MKStoreKit.

Development vs Release Python Code

I am currently developing a Python application (for PhD research) which I continually performance test, simply by recording the runtime of various parts.

A lot of the code is related only to the testing environment and would not exist in the real world application, at the moment I comment out these parts when testing. This requires me to remember which calls refer to test only components (they are quite interleaved so I cannot group the functionality).

I was wondering if there was a better solution to this, the only idea I have had so far is creation of a 'mode' boolean and insertion of If statements, though this feels needlessly messy. I was hoping there might be some more standardised testing method that I am naive of.

Thank you in advance

CTS instrumentation target package

I'm trying to test my testcase in CTS console. When I run my testcase via android studio,the instrumentation is get installed and all the tests pass the cts plan. But when I run the cts plan without the android studio (I take the test APK from the outputs),all the tests fail with this error:

Unable to find instrumentation target package: In my gradle I added this:

applicationId "x"
    testApplicationId "x.test"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

I tried to add an instrumentation tag to the manifest tag also targeting both packages (x and x.test).

What am I missing?

samedi 27 août 2016

Is it currently possible to run Arquillian tests on Spring beans?

From what little experience I have of running Arquillian tests with the Arquillian Spring Framework Extension, it seems to me that things are severely broken at the moment.

I've tried running a test even simpler than the Spring Inject example from the arquillian showcase project (i.e. no classes, applicationContext.xml only, and a single test that has assertTrue(true) as its body).

The relevant dependencies are largely the same as those in the Spring Inject example save for version differences.

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.jboss.arquillian</groupId>
                <artifactId>arquillian-bom</artifactId>
                <version>1.1.11.Final</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependency>
        <groupId>org.jboss.arquillian.extension</groupId>
        <artifactId>arquillian-service-integration-spring-inject</artifactId>
        <version>1.1.0.Alpha1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.extension</groupId>
        <artifactId>arquillian-service-deployer-spring-3</artifactId>
        <version>1.0.0.Beta3</version>
        <scope>test</scope>
    </dependency>

I even included parts of that project's parent pom just to be sure.

    <dependency>
        <groupId>org.jboss.arquillian.protocol</groupId>
        <artifactId>arquillian-protocol-servlet</artifactId>
        <scope>test</scope>
    </dependency>

However this only resulted in the following error

Caused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.config.EmbeddedValueResolver from [Module "deployment.e5488c33-14dd-41b6-8996-d616c11cbbb5.war:main" from Service Module Loader]

I've tried using the Shrinkwrap resolver to include the necessary jars, but that error still showed up.

So tell me, is the Arquillian testing of Spring beans and components currently broken?

P.S: The version of Spring I am using is 4.3.2.

Installed app in Django not found when running tests

I have a pretty simple Django app, that I am trying to run unit tests on. In my tests.py file I am trying to import the parent apps views file. I tried 'from . import views' but got an error:

SystemError: Parent module '' not loaded, cannot perform relative import

I read that when a relative path does not work, you can try using an absolute path so I tried 'from menu import views' but than got another error:

ImportError: No module named 'menu'

When I run a local server for the application it works just fine. Its only when I run 'coverage run 'coverage run menu/tests.py'. Since it is running fine, and the module is in my setting's installed apps, Im not entirely sure why this is happening.

menu/tests.py

import unittest

from menu import views

class ModelTestCase(unittest.TestCase):
    def setUp(self):
        pass

    def test_menu(self):
        pass

if __name__ == '__main__':
    unittest.main()

settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'menu',
    'django_nose'
)

Selenium: selecting all inner elements

I select all <a> elements inside all <td> elements

<td class="thread">
    <i class="ter green"></i>
    <a href="/forum/threads/12/">Something about...</a>
    <p class="info">Author</p>
</td>

I use the following:

driver.findElements(By.cssSelector("td.thread a"));

However, I'm getting much more elements than there are on the page. What am I doing wrong?

Difference between model based testing and model driven testing

After hours of searching on google on the above mentioned topic. I am unable to contrast the difference between model based testing and model driven testing. Tons of definitions are there,. But there is no clear definition with real world example.

Can anyone please help me understand the difference between these two with the help of real world example.

How to mock components within unit tests for Click-based CLI applications?

I'm not sure if this is the best fit for here or the Programmers Stack Exchange, but I'll try here first and cross-post this over there if it's not appropriate.

I've recently developed a web service and I'm trying to create a Python-based command-line interface to make it easier to interact with. I've been using Python for a while for simple scripting purposes but I'm inexperienced at creating full-blown packages, including CLI applications.

I've researched different packages to help with creating CLI apps and I've settled on using click. What I'm concerned about is how to structure my application to make it thoroughly testable before I actually go about putting it all together, and how I can use click to help with that.

I have read click's documentation on testing as well as examined the relevant part of the API and while I've managed to use this for testing simple functionality (verifying --version and --help work when passed as arguments to my CLI), I'm not sure how to handle more advanced test cases.

I'll provide a specific example of what I'm trying to test right now. I'm planning for my application to have the following sort of architecture...

architecture

...where the CommunicationService encapsulates all logic involved in connecting and directly communicating with the web service over HTTP. My CLI provides defaults for the web service hostname and port but should allow users to override these either through explicit command-line arguments, writing config files or setting environment variables:

@click.command(cls=TestCubeCLI, help=__doc__)
@click.option('--hostname', '-h',
              type=click.STRING,
              help='TestCube Web Service hostname (default: {})'.format(DEFAULT_SETTINGS['hostname']))
@click.option('--port', '-p',
              type=click.IntRange(0, 65535),
              help='TestCube Web Service port (default: {})'.format(DEFAULT_SETTINGS['port']))
@click.version_option(version=version.__version__)
def cli(hostname, port):
    click.echo('Connecting to TestCube Web Service @ {}:{}'.format(hostname, port))
    pass


def main():
    cli(default_map=DEFAULT_SETTINGS)

I want to test that if the user specifies different hostnames and ports, then Controller will instantiate a CommunicationService using these settings and not the defaults.

I imagine that the best way to do this would be something along these lines:

def test_cli_uses_specified_hostname_and_port():
    hostname = '0.0.0.0'
    port = 12345
    mock_comms = mock(CommunicationService)
    # Somehow inject `mock_comms` into the application to make it use that instead of 'real' comms service.
    result = runner.invoke(testcube.cli, ['--host', hostname, '--port', str(port)])
    assert result.exit_code == 0
    assert mock_comms.hostname == hostname
    assert mock_comms.port == port

If I can get advice on how to properly handle this case, I should hopefully be able to pick it up and use the same technique for making every other part of my CLI testable.

For what it's worth, I'm currently writing tests in pytest and this is the extent of the tests I've got so far:

import pytest
from click.testing import CliRunner

from testcube import testcube


# noinspection PyShadowingNames
class TestCLI(object):
    @pytest.fixture()
    def runner(self):
        return CliRunner()

    def test_print_version_succeeds(self, runner):
        result = runner.invoke(testcube.cli, ['--version'], foo='bar')

        from testcube import version
        assert result.exit_code == 0
        assert version.__version__ in result.output

    def test_print_help_succeeds(self, runner):
        result = runner.invoke(testcube.cli, ['--help'])
        assert result.exit_code == 0

Rails: Can I test for the presence of a button_to?

My site had dozens of instances of "link_to". I decided to change most of them to "button_to" for better appearance. The lines of my test that used to check for the presence of those links are no good anymore.

assert_select "a", :href => user_path(@seminar.teacher), text: "Your Teacher Profile", count: 2

The test doesn't work correctly with

assert_select "button", etc...

Is there a way to adjust the test to find the button_to instances? From my initial searches, it seems like there isn't.

I'm also considering simply cutting those lines from the tests, since I've read in another article that simply testing for the presence of display items isn't a very useful way to use rails tests.

Thanks in advance for any insight!

Find Recyclerview using Espresso

Is there a way to find view of kind in Espresso? I want to find a RecyclerView in the view hierarchy and carry out scroll action. The id and tag are not fixed i.e not possible to use withId or withTag etc.

Thanks!

vendredi 26 août 2016

Security Exception While Running TestNG test in Eclipse juno

i am getting below error while trying to run testng in eclipse juno

Exception in thread "main" java.lang.NoSuchMethodError: org.testng.internal.Utils.defaultIfStringEmpty(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; at org.testng.remote.AbstractRemoteTestNG.setHost(AbstractRemoteTestNG.java:59) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:137) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:57)

Plugin:6.9.12 testng jar:6.8.5 IDE:Eclipse Juno

Run Multiple Nightwatch Tests -- One at a Time

How can I run nightwatch tests with the same tag one-at-a-time?

Right now, running multiple tests will cause them to run at the same time.

Black Box can cover white box testing

Hi I am new to SW testing.

WBT - Developer does this, makes sure each line is executed and checks all conditional statement.

BBT - in Black Box, I can do the same thing as intended in WBT, I can input various parameters and check for output, make sure I cover all conditional statements by making test case and also cover loop execution.

What is the real difference between White box and Black Box testing? For me it looks like, do a extensive input, corner case coverage BBT and that is going to be a WBT.

ReactTestRenderer: lib to find elements inside tree

I have the following code for my test

import React from 'react';
import renderer from 'react/lib/ReactTestRenderer';

import Accordion from '../../src/js/components/Accordion';
import AccordionPanel from '../../src/js/components/AccordionPanel';

// needed because this:
// http://ift.tt/2bTSbrm
jest.mock('react-dom');

describe('Accordion', () => {
  it('has correct default options', () => {
    const component = renderer.create(
      <Accordion>
        <AccordionPanel heading="First Title">
          <p>test</p>
        </AccordionPanel>
      </Accordion>
    );
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
});

Now I would like to call an onClick function in a property inside a children. I'm wondering if there is a lib that would be able to walk through the component.toJSON() tree and find an element given a query. For example:

findAllByType(tree, 'header');

The return of this call would be an array of header elements inside the tree.

I could create a recursive function to walk through the tree but I'm wondering if there is a lib out there that does it for me. I tried looking around but I could not find any.

Other possible utility functions for this would be:

  • findFirstByType(tree, type)
  • findAllByClassName(tree, className)
  • findFirstByClassName(tree, className)
  • findAllBy(tree, field, value)
  • findFirstBy(tree, field, value)

How to unit test Bluetooth accessories?

I have an application with an Android and an iOS version, both of which function primarily by connecting and sending/receiving messages to/from Bluetooth accessories.

  • iOS uses ExternalAccessory to connect to Bluetooth devices
  • Android uses BluetoothDevice to connect to Bluetooth devices

I want to write unit tests to make them reliable.

Note that I am not looking to test what it sends/receives to the bluetooth device based on input/output (I already have that tested with stream wrappers). I need to test behavior like:

  • The bluetooth accessory has disconnected in the middle of an operation
  • A connection has failed

How to go about it?

Integration testing with Karma

Till now, I've done all my testing with just Jasmine and jQuery to automate the browser. I am starting to explore Karma but it seems to be set up only for unit tests with involve loading HTML fragments as test fixtures and I find no way to load a whole web page. Am I missing something or is this simply the wrong tool for what I am trying to do?

Thanks.

what type of file will be suitable for storing locator in Web Automation Testing using PHPUnit?

i want to store my locator in a different file, i want to store three field ,i can store them in text file with three column but reading the a value(in php ) will be little bit complex ,is there any file type which let me store the values and Reading is little simpler??

Selenium Web Driver - Java - TestNG - Assert.assertEquals how to compare actual result with the range between expected result

I have test scenario where actual result is fix percentage For example 135.68% but I want to compare actual result with the Expected result which is in range For example 130.00 to 136.00. If actual result fall between the range of 130.00 to 136.00 then test is pass otherwise test is fail.

I am using following Assert statement but no luck:

Assert.assertEquals("130.00 to 136.00", driver.findElement(By.xpath("//*[@id='app-banner']/div[1]/div/h2")).getText());

Other element would receive the click error

How do you click the cart icon if the error says element is not clickable? I already tried it using inspect element but to no avail. I've been doing this for hour and I still don't get how to click the cart icon.

driver.get("http://ift.tt/2bUsBTY");
        driver.findElement(By.cssSelector(".hover-green")).click();
        driver.findElement(By.cssSelector("#ember781")).sendKeys("deumdummy@yahoo.com");
        driver.findElement(By.cssSelector("#ember783")).sendKeys("password");
        driver.findElement(By.cssSelector("button.btn.green.block")).click();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//span[contains(@style,'background-image: url(http://ift.tt/2ceCXkJ)')]")).click();

        WebElement element = driver.findElement(By.cssSelector(".btn.green.medium"));
        Actions actions = new Actions(driver);
        actions.moveToElement(element).click().perform();

        driver.findElement(By.xpath("//img[@alt='Acana Duck And Bartlett Pear Singles Formula']")).click();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.findElement(By.cssSelector("a.btn.green.huge.block")).click();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);


        driver.findElement(By.cssSelector(".ember-view.cart-icon")).click();
        WebDriverWait wait = new WebDriverWait(driver,30);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".btn.green.jumbo]"))); 

run Jasmine tests after initial function calls

I'm writing Jasmine tests for a Node.js API. I'm trying to test the create a user functionality. The test would look like this:

describe('User test', function() {
  describe('Post /api/saveUser'), function() {
    it('saves a new user', function(done) {
      request.post({url: 'http://website/api/saveUser', form:{email:testU.email, password:testU.password}, headers: {'authorization': adminU.jwt}}, function(err, res, body) {
        expect(res.statusCode).toBe(200);
      });
    });
  });
});

So I need to authenticate the admin user (adminU) in the spec to get the valid token to pass in the request. This is done using another endpoint.

request.post({url: 'http://website/api/authenticate', form:{email:adminU.email, password: adminU.password}}, function(err, res, body) {
  adminUser.jwt = JSON.parse(res.body).token;
});

But how do I combine these. If I slot the authentication code above the User test block, the user tests are run before the response from the authentication endpoint is received. The obvious choice is to wrap the user tests in the callback from the authenticate api, but then when I run the tests Jasmine doesn't actually run them.

What's the best way to use the results of a callback in the Jasmine specs?

is there any tool cover GUI testing?

The web page developed through GWT, it has three buttons Add,Edit and Delete for that tester written test case to cover Add and Delete button. Test case is missing for Edit button. So how to find out Edit button not tested or used? I have access to only GUI , not to the test code.

Any suggestion how to find out missing test case on Edit button?

-Vikram

How to setup Selenium test environment with eclipse on PC?

I'm new bee in automation testing and want to start with Selenium testing. Please guide to setting up selenium testing environment using eclipse on PC.

Thanks

Is there any js library available to test layout of a webpage & compare two versions?

I am looking for a library similar to backstop js but having feature to ignore comparing dynamic regions on the web page or just comparing and checking if two versions have same layout.

Getting error: Found argument '--webdriver-port' which wasn't expected, or isn't valid in this context

When I am running my selenium code I get the error "error: Found argument '--webdriver-port' which wasn't expected, or isn't valid in this context"

I am having Firefox 48.0 Using gecko driver i have initialized browser. And getting the above mentioned error.

Rest service testing using Jmeter authorization issue- Need application to be logged in browser to run Rest call from any client

I want to test rest service thorough Jmeter, I have tested Rest call using postman and its working fine. thing is to run rest service from any client like postman, i need to login to my application first in browser and after login rest call will work in RESTClient(Firefox). but in case of Jmeter how to run then. i have added authorization. (Username and password) using HTTP Authorization manager still facing. even i have added bean shell script bellow

import org.apache.commons.codec.binary.Base64; byte[] encodedUsernamePassword = Base64.encodeBase64("harshal.shewale1@viewics.com:Harshal@1".getBytes()); vars.put("base64HeaderValue",new String(encodedUsernamePassword));

still not running rest. giving error as a Bad credentials.

someone please guide me.

Slow Polymer testing (WCT) on windows machines

I've developed an application using Polymer 1.0. My developer computer is a Mac, and I've not had any problems during development process.

However, when I clone my application on a Windows machine (Windows 10), the tests don't work at all.

Whenever I execute polymer test or wct the command blocks the terminal and never ends.

On MACOS or Linux it works perfectly.

Which tests to choose from a large regression test suite?

I was once asked in interview that on what basis u decide which tests to choose from a large regression test suite for the regression testing. Any suggestions?

Robot framework resource file not found

I want to use a resource file with the name clean_environment.robot on windows. It is in the same folder like my robot file (C:\Users\xxxxx\Desktop\git\src), which is callig the resource file.

Basic file 30.robot:

** Settings **
Resource    clean_environment.robot

** Test Cases **
MyTestCase
    Clean environment

I get the error:

[ ERROR ] Error in file
'C:\Users\xxxxx\Desktop\git\src\30.robot': 
Resource file 'Clean environment' does not exist.

Getting error "org.openqa.selenium.WebDriverException: java.net.ConnectException: Connection refused:"

I am using selenium webdriver for the testing application. i am using using Marionettedriver for the browser. however when I run the code it gives the error "org.openqa.selenium.WebDriverException: java.net.ConnectException: Connection refused:" I have check the system path also no issue in the same. so please suggest how to solve the error''

XHR error (404 not found) loading @angular/core/testing

I am using Angular 2 RC 5 and wanna integrate Jasmine. Whenever I try to import @angular/core/testing I get an 404 http://localhost:3000/@angular/core/testing not found error. I tried to google it and everything but nothing helped. I followed the official Angular site to set up Jasmine.

package.json

    {
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings",
    "lite-server-test": "lite-server --config=liteserver-test-config.json",
    "test": "tsc && concurrently \"npm run tsc:w\" \"npm run lite-server-test\" "
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0-rc.5",
    "@angular/compiler": "2.0.0-rc.5",
    "@angular/core": "2.0.0-rc.5",
    "@angular/forms": "0.3.0",
    "@angular/http": "2.0.0-rc.5",
    "@angular/platform-browser": "2.0.0-rc.5",
    "@angular/platform-browser-dynamic": "2.0.0-rc.5",
    "@angular/router": "3.0.0-rc.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.5",
    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2-in-memory-web-api": "0.0.15",
    "bootstrap": "^3.3.6"

  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "jasmine-core": "2.4.1",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings": "^1.0.4"
  }
}

unit-tests.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title>Ng App Unit Tests</title>
    <link rel="stylesheet" href="/node_modules/jasmine-core/lib/jasmine-core/jasmine.css">
    <script src="/node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
    <script src="/node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
    <script src="/node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>

    <script src="app/1st.spec.js"></script>
</head>
<body>
<script src="/node_modules/systemjs/dist/system.src.js"></script>

<script>

    System.config({
        packages: {
            'app': {defaultExtension: 'js'}
        }
    });

    System.import('app/1st.spec')

            .then(window.onload)
            .catch(console.error.bind(console));
</script>
</body>
</html>

my test file

import { Hero } from './hero';
import {TestBed, addProviders} from "@angular/core/testing";
let service: Hero;
describe('Hero', () => {
    beforeEach(() => {
       addProviders([Hero]);
    });

    it('has name', () => {
        let hero: Hero = {id: 1, name: 'Super Cat'};
        expect(hero.name).toEqual('Super Cat');
    });
    it('has id', () => {
        let hero: Hero = {id: 1, name: 'Super Cat'};
        expect(hero.id).toEqual(1);
    });
    it('inject', () => {
        expect(service.id).toBeNull();
    });
});

Without using /core/testing it works fine.

jeudi 25 août 2016

PeopleSoft Test Framework test execution error

enter image description hereenter image description hereTest is stopping here. it is not going to further steps, peoplesoft test framework version 8.55 internet explorer 11 ( multi os / windows 8.1)

Coded UI Test Button Click Not Working

I have a coded ui test on web form. It has the event :

Mouse.Click(uINextButton1, new Point(20, 7));

The problem is:

  1. Button does actually get clicked
  2. But the Page does not give any response, i.e. the button's job is to forward to a next page of web form but it doesn't.

or in short, The Button click event does not fire when clicked by the Coded UI Test. When clicked manually (outside of the test) it works. When clicked manually inside of the coded ui test, it again doesn't work.

I tested the web form application on internet explorer (same as coded ui) manually. The same button works when I click by mouse manually (outside of the test) i.e. the next page actually loads.

This has been troubling me for a week now. If any solution or pointers, plz help.

Thanks.

Correlation between sanity testing and regression testing

After reading about many posts about smoke and sanity testing i have concluded following about testing order:

Smoke testing(generalized health checkup)---then--> Sanity Testing(checking some main functionalities to somewhat more deeper level)(Specialized health checkup)----------------then--------> Functional testing(full functionality checking at deeper levels)

In many posts i have read that sanity is subset of regression testing. But according to above mentioned order it seems that sanity is subset of functional testing. Can anyone elaborate that how sanity is subset of regression testing?

Confusion about sanity testing of software

I have read several posts regarding smoke and sanity testing. All are almost confusing. Neither explaining them clearly,just repeating the matter except some two or three posts and based on that two or three posts i concluded that following is the formal process:

Smoke testing(generalized health checkup)---then--> Sanity Testing(checking some main functionalities to somewhat more deeper level)(Specialized health checkup)----------------then--------> Functional testing(full functionality checking at deeper levels)

Am i right in above concept?

I have confusion regarding when sanity is performed. Smoke is performed when build comes very first time. But when sanity is performed? Is sanity is performed only after every smoke OR it is performed every time build undergoes some change(i.e. even when smoke is not performed because smoke is performed only first time build comes) OR in both cases?

Grantee the method of child class return a correct data type with py.test

Java or Python 3.5 is not an option for my organization for now. and I want to make sure the our code has 100% coverage. But I run into the following issues.

in a.py (By developer01)

class API1(object):

    def f(self):
        """return a list of int"""
        raise NotImplementedError()

in b.py (By developer02)

class API1Impl1(a.API1):

    def f(self):
        return 3

in test_b.py(By developer02)

def test_api1_impl1():
    api1impl = API1Impl1()
    assert api1impl.f() == 1

In the above case, if we use py.test cov function, we still can see the 100% coverage. but that's not what I want.

As a developer01, can I did some magic so that any others test their API1ImplX class, the following code will be executed.

ret = api1impl.f()
assert isinstance(ret) and all([isinstance(i, int) for i in ret])

Django client test (get, post) response load data from main db instead fixtures loaded in test db

I'm new in Django, and I have this problem: I use self.client to test routes in my app. e.g.

class BookSell(TestCase):
    fixtures = [
        'sellers.yaml',
        'books.yaml'
          ...
    ]

    def test_get_book_sell(self):
        response = self.client.get('/sell/book-sell')
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Book Sell")
        self.assertContains(response, "El Quijote")#book name 

The view method linked to that path should load some data from the database and then render it. But when I run

python manage.py test app_name

it doesn't load data from fixtures, because the response doesn't contain "El Quijote". Only when I run:

python manage.py loaddata fixture_name.yaml ...

and then run again the tests the view method loads data from the database.

So I conclude that when I run the tests, my views methods load data from main database instead of test database

What is that I'm doing wrong? Is there a way to load just data from test database?

django version: 1.9.4 python version: 2.7.6 I'm sure that the fixtures load with sucess in test database