jeudi 30 avril 2015

Is there a site that loads slowly on purpose?

I'm working on the system that embeds a browser object. One of the requirements is to put a "Please wait" message if the page takes too long to load.

If there a site out there that deliberately loads slowly for the purpose of testing?

I don't care what the content is, I just want it to make 5+ seconds to load.

rspec assigning variables - ERROR: expected: "Completed" got: "pending" (compared using ==)

I am testing my controller in ruby on rails using RSPEC and Factories (using factory girl) Controller Code:

class JobsController < ApplicationController
  before_action :authenticate_member!
  before_action :set_job

def complete
  @job.status = "completed"
  @job.save!
  Event.where("job_id = ? AND starts_at > ?", @job.id, DateTime.now).destroy_all
  redirect_to scheduler_path
  puts @job.inspect
end

  def set_job
    @job = Job.find(params[:id] || params[:job_id])
  end

end

RSPEC Code:

describe JobsController do
  login_user

  before do 
    @job=FactoryGirl.create(:job)
  end

  describe "Complete Action" do 
    it "sets job status to complete" do 
      puts @job.inspect
      get :complete, :id=>@job.id
      @job.status.should eq("Completed")
    end
  end

The Error:

 expected: "Completed" got: "pending" (compared using ==)

Note the output from the controller code is:

#<Job id: 12, name: nil, status: "completed">

So I know its changed within the controller, however why does it go back to "pending" in factory girl ? Note 2: Pending is the default value. Am i mis-understanding the relationship between the controller and factory girl ?

Help please?!

Django REST framework: AttributeError: object has no attribute 'serializer'

I have some issues with writing tests against Django REST API framework. I have Python 2.7.6 on Mac OS v.10.10.3, Django==1.6.5 and djangorestframework==3.1.1. I'm trying to write a couple of tests against Django REST framework.

I have a dummy test view for the API:

class TestApiView(APIView):
    def get(self, request, format=None):
        return Response(status=status.HTTP_404_NOT_FOUND) 

It works just fine while I'm calling it:

(venv)bash-3.2# curl -H "Accept: application/json; indent=2" -i --request GET "http://ift.tt/1JcqKCi"
HTTP/1.0 404 NOT FOUND
Date: Thu, 30 Apr 2015 18:35:09 GMT
Server: WSGIServer/0.1 Python/2.7.6
Vary: Accept, Cookie
Allow: GET, HEAD, OPTIONS

But when I want to lunch a Test against that view it raises exception. My test code:

from rest_framework.test import APIClient

client = APIClient()
print client.get('/api/v1/client/test/', format='json')

This code raises exception:

Internal Server Error: /api/v1/client/test/
Traceback (most recent call last):
  File "/Users/user/dev/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 137, in get_response
    response = response.render()
  File "/Users/user/dev/venv/lib/python2.7/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/response.py", line 59, in rendered_content
    ret = renderer.render(self.data, media_type, context)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/renderers.py", line 333, in render
    form = data.serializer
AttributeError: 'NoneType' object has no attribute 'serializer'
Traceback (most recent call last):
  File "/Users/user/dev/managerv2/tests.py", line 20, in <module>
    print client.get('/api/v1/client/test/', format='json')
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/test.py", line 160, in get
    response = super(APIClient, self).get(path, data=data, **extra)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/test.py", line 86, in get
    return self.generic('GET', path, **r)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/compat.py", line 222, in generic
    return self.request(**r)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/test.py", line 157, in request
    return super(APIClient, self).request(**kwargs)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/test.py", line 109, in request
    request = super(APIRequestFactory, self).request(**kwargs)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/django/test/client.py", line 444, in request
    six.reraise(*exc_info)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 137, in get_response
    response = response.render()
  File "/Users/user/dev/venv/lib/python2.7/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/response.py", line 59, in rendered_content
    ret = renderer.render(self.data, media_type, context)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/renderers.py", line 333, in render
    form = data.serializer
AttributeError: 'NoneType' object has no attribute 'serializer'

I have almost the same issue with views based on mixins.ListModelMixin - it works fine, but raises exception during testing.

View definition:

class ListTestView(mixins.ListModelMixin, generics.GenericAPIView):

    pagination_class = paginators.StandardResultsSetPagination

    def get(self, request, format=None, *args, **kwargs):
        self.serializer_class = TestListSerializer
        self.queryset = Client.objects.all()
        return self.list(request, *args, **kwargs)

Calling this view from the test client:

print client.get('/api/v1/client/list/', format='json')

raises this exception:

Internal Server Error: /api/v1/client/list/
Traceback (most recent call last):
  File "/Users/user/dev/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 137, in get_response
    response = response.render()
  File "/Users/user/dev/venv/lib/python2.7/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/response.py", line 59, in rendered_content
    ret = renderer.render(self.data, media_type, context)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/renderers.py", line 333, in render
    form = data.serializer
AttributeError: 'OrderedDict' object has no attribute 'serializer'
Traceback (most recent call last):
  File "/Users/user/dev/managerv2/tests.py", line 22, in <module>
    print client.get('/api/v1/client/golden_state/list/1/', format='json')
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/test.py", line 160, in get
    response = super(APIClient, self).get(path, data=data, **extra)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/test.py", line 86, in get
    return self.generic('GET', path, **r)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/compat.py", line 222, in generic
    return self.request(**r)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/test.py", line 157, in request
    return super(APIClient, self).request(**kwargs)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/test.py", line 109, in request
    request = super(APIRequestFactory, self).request(**kwargs)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/django/test/client.py", line 444, in request
    six.reraise(*exc_info)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 137, in get_response
    response = response.render()
  File "/Users/user/dev/venv/lib/python2.7/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/response.py", line 59, in rendered_content
    ret = renderer.render(self.data, media_type, context)
  File "/Users/user/dev/venv/lib/python2.7/site-packages/rest_framework/renderers.py", line 333, in render
    form = data.serializer
AttributeError: 'OrderedDict' object has no attribute 'serializer'

Any suggestions? Many thanks!

How to upload file with Selenium on Equafy

I've created a test on equafy.com platform and I need to upload a file using Selenuim. In my case the file is png image, but I cannot find a way to upload any type of file.

I´m using ShrinkWrap to deploy a test on a maven web project, but it can't find the persistence.xml of the project

I'm building a test of a java maven project using Arquilian to create a deployment, but it cant find the correct persistence.xml. It's locating the one on the project to be tested and not the one defined on the test project.

Here's my test class

    @FixMethodOrder(MethodSorters.NAME_ASCENDING)
    @RunWith(Arquillian.class)
    public class PurchaseServiceTest {

        public static final String DEPLOY = "Callys.service";
        public static String URLRESOURCES = "src/main/webapp";

        @ArquillianResource
        URL deploymentURL;

        @Deployment
        public static Archive<?> createDeployment() {

            return ShrinkWrap.create(WebArchive.class, DEPLOY + ".war")     
           .addAsLibraries(DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("pom.xml").artifact("co.edu.uniandes.Callys:Callys.logic:0.0.1").resolveAsFiles())
           .addAsWebResource(new File(URLRESOURCES, "index.html"))
           .merge(ShrinkWrap.create(GenericArchive.class).as(ExplodedImporter.class).importDirectory(URLRESOURCES + "/src/").as(GenericArchive.class), "/src/", Filters.includeAll())
           .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml")
           .addAsWebInfResource(new File("src/main/webapp/WEB-INF/beans.xml"))
           .setWebXML(new File("src/main/webapp/WEB-INF/web.xml"));
}

I added as libraries the classes on the project to test, then added the web resources to run the Selenium tests, and tried to add as a resource the persistence.xml related to the database.

    .addAsResourcce("META-INF/persistence.xml", "META-INF/persistence.xml") 

But when i run it this happens

    abr 30, 2015 1:59:07 PM org.glassfish.deployment.admin.DeployCommand execute
    GRAVE: Exception while preparing the app : Invalid resource : { ResourceInfo : (jndiName=java:app/jdbc/ISIS2603Callys__pm), (applicationName=Callys.service) }
   com.sun.appserv.connectors.internal.api.ConnectorRuntimeException: Invalid resource : { ResourceInfo : (jndiName=java:app/jdbc/ISIS2603Callys__pm), (applicationName=Callys.service) }
at org.glassfish.jdbcruntime.service.JdbcDataSource.validateResource(JdbcDataSource.java:81)
at org.glassfish.jdbcruntime.service.JdbcDataSource.setResourceInfo(JdbcDataSource.java:62)
at org.glassfish.jdbcruntime.JdbcRuntimeExtension.lookupDataSourceInDAS(JdbcRuntimeExtension.java:136)
at com.sun.enterprise.connectors.ConnectorRuntime.lookupDataSourceInDAS(ConnectorRuntime.java:589)
at com.sun.enterprise.connectors.ConnectorRuntime.lookupPMResource(ConnectorRuntime.java:517)
at org.glassfish.persistence.common.PersistenceHelper.lookupPMResource(PersistenceHelper.java:63)
at org.glassfish.persistence.jpa.ProviderContainerContractInfoBase.lookupDataSource(ProviderContainerContractInfoBase.java:71)
at org.glassfish.persistence.jpa.PersistenceUnitInfoImpl.<init>(PersistenceUnitInfoImpl.java:108)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:142)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:107)
at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:223)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:230)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:922)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:431)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:133)
at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:109)
at org.jboss.arquillian.container.glassfish.embedded_3_1.GlassFishContainer.deploy(GlassFishContainer.java:227)
at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$3.call(ContainerDeployController.java:161)
at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$3.call(ContainerDeployController.java:128)
at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.executeOperation(ContainerDeployController.java:271)
at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.deploy(ContainerDeployController.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
at org.jboss.arquillian.container.impl.client.ContainerDeploymentContextHandler.createDeploymentContext(ContainerDeploymentContextHandler.java:78)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.container.impl.client.ContainerDeploymentContextHandler.createContainerContext(ContainerDeploymentContextHandler.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.container.impl.client.container.DeploymentExceptionHandler.verifyExpectedExceptionDuringDeploy(DeploymentExceptionHandler.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:135)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:115)
at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67)
at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$1.perform(ContainerDeployController.java:95)
at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$1.perform(ContainerDeployController.java:80)
at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.forEachDeployment(ContainerDeployController.java:263)
at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.forEachManagedDeployment(ContainerDeployController.java:239)
at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.deployManaged(ContainerDeployController.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:135)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:115)
at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67)
at org.jboss.arquillian.container.test.impl.client.ContainerEventController.execute(ContainerEventController.java:101)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:135)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:115)
at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.beforeClass(EventTestRunnerAdaptor.java:80)
at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:182)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:314)
at org.jboss.arquillian.junit.Arquillian.access$100(Arquillian.java:46)
at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:199)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:147)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)

It seems it's locating the persistence.xml on the Callys.logic META-INF folder and not the Callys.service one.

Capybara: Sometimes finds elements, sometimes doesn't

Hello dear Stackoverflowers.

I'm having some seriously insanely annoying trouble with my capybara test. It seems to have a mind of its own and will sometimes decide to run with zero issue and sometimes decide to not find elements, click anything and generally just suck. I have no idea why this is.

I've been researching for days trying to find sure up my logic, find the 'best' ways of finding and clicking elements or filling in fields and haven't gotten any further. Please help, if I still had hair I would be pulling it out.

Also I'm using the Selenium Web Driver. All gems are up to date.

Thanks in advance.

It will randomly decide to not click on 'Amtrak 1234' and sometimes entirely miss the find('#atedrop4').click or will decide to click elements not even close being specified in my test. I'm very confused.

  click_link 'Amtrak 1234'
  find('#atedrop4').click
  find('.ategoogle').click
  new_window=page.driver.browser.window_handles.last
  page.driver.browser.switch_to.window(new_window) do
    expect(page).to have_content "evan@tripwing.com"
    page.driver.browser.close
  end
  click_link 'Amtrak 1234'



  click_link 'Sixt Autoverhuur'
  find('#atedrop7').click
  find('.ategoogle').click
  new_window=page.driver.browser.window_handles.last
  page.driver.browser.switch_to.window(new_window) do
    expect(page).to have_content "evan@tripwing.com"
    page.driver.browser.close
  end
  click_link 'Sixt Autoverhuur'


  click_link 'Hotel 717'
  find('#atedrop8').click
  find('.ategoogle').click
  new_window=page.driver.browser.window_handles.last
  page.driver.browser.switch_to.window(new_window) do
    expect(page).to have_content "evan@tripwing.com"
    page.driver.browser.close
  end
  click_link 'Hotel 717'

  click_link 'Car Transfer from 22 Wilson Ave, Brooklyn, NY 11237, USA'
  find('#atedrop9').click
  find('.ategoogle').click
  new_window=page.driver.browser.window_handles.last
  page.driver.browser.switch_to.window(new_window) do
    expect(page).to have_content "evan@tripwing.com"
    page.driver.browser.close
  end
  click_link 'Car Transfer from 22 Wilson Ave, Brooklyn, NY 11237, USA'

tcl tcltest unknown option -run

When I run ANY test I get the same message. Here is an example test:

package require tcltest
namespace import -force ::tcltest::*
test foo-1.1 {save 1 in variable name foo} {} {
    set foo 1
} {1}

I get the following output:

WARNING: unknown option -run: should be one of -asidefromdir, -constraints, -debug, -errfile, -file, -limitconstraints, -load, -loadfile, -match, -notfile, -outfile, -preservecore, -relateddir, -singleproc, -skip, -testdir, -tmpdir, or -verbose

I've tried multiple tests and nothing seems to work. Does anyone know how to get this working?

How to write tests for writers / parsers? (Python)

I have written a piece of software in Python that does a lot of parsing and a lot of writing files to disk. I am starting to write unit tests, but have no idea how to unit test a function that just writes some data to disk, and returns nothing.

I am familiar with unittest and ddt. Any advice or even a link to a resource where I could learn more would be appreciated.

JUnit Testing equivalence partitioning, where parameters are being received from JTextField rather than being passed into method

Ok so Im a bit confused and cant find a clear answer to my question.What I want to do is check if an input condition specifies a range of values ie. Greater than one char.I have already handled for this in my code but need to create the JUnit for some testing as part of a college assignment.I will post my code here. This is the method I want to check and it is in a class called AccountCreation.

Thanks

public void CreateAccountButtonClicked()
    {
        //check database for username multiple entries 
        DbCheck check = new DbCheck();
        String userName = textField.getText();
        String password = passwordField.getText();
        //if statement to make sure username and password have at least one character
        if(userName.length()<1 ||password.length()<1)
        {
            JOptionPane.showMessageDialog(null, "Please Enter at least one character in each field");
        }
        else{
        boolean checkCredentials = check.checkAcc(userName);
        if(checkCredentials == false)
        {
            int score=0;
            DbConnect connect = new DbConnect();
            connect.setData(userName,password,score);


            this.setVisible(false);
            new GameSelection().setVisible(true);
        }
        else
        {
            //inform user if user name is already taken.
            JOptionPane.showMessageDialog(null, "User name already exists");
        }
        }


    }
}

JUnit testing a java method,is it normal to test methods without a return type or should i use a different type of testing for them?

I am testing a program as part of a college assignment, i have tested some methods that return a Boolean to see if they are correct, im wondering is it standard practice to check void methods with JUnit? or is there another way.I will post one of the methods here as an example. Thanks

It is a quiz game program and this method accepts an int, which is defining the year the questions will be selected from.if statements then check the year passed in and sets the questions from a question class(that are defined as objects) not sure whether you need to know that or not to answer my question.

Thanks

  public GamePlay(int decade)
    {
        this();
        questions = null;
        if(decade== 1960)
        {
            questions = Questions.QuestionSetFrom60s();


        }
        else if(decade== 1970)
        {
            questions = Questions.QuestionSetFrom70s();

        }
        else if(decade== 1980)
        {
            questions = Questions.QuestionSetFrom80s();

        }
        else if(decade== 1990)
        {
            questions = Questions.QuestionSetFrom90s();

        }
        else if(decade== 2000)
        {
            questions = Questions.QuestionSetFrom2000s();

        }
        else if(decade== 2010)
        {
            questions = Questions.QuestionSetFrom2010s();

        }
        ImageIcon pic = new ImageIcon(questions[questionIndex].mediaFilePath);
        lblMediaPlayer.setIcon(pic);

        questionIndex = 0;

        lblDisplayQuestion.setText(questions[questionIndex].textQuestion);
    }

TestLink integration in Jenkins

can someone tell me, where the testng-results.xml is processed by TestLink?

I guess some explanation is required: I've got a system build by using the jenkins-testlink tutorial. When I build the project in jenkins, TestLink somehow process the results to get them into the test execution dashboard. I would like to know in which funktion or file TestLink is doing this.

Executing test from another test in google test framework

Let's say I have two tests in the same testcase: writeTest and readTest

TEST_F(testcase, writeTest)
{
  ASSERT_EQ(OK, write_something();
} 

TEST_F(testcase, readTest)
{
  ASSERT_EQ(OK, write_something();
  ASSERT_EQ(OK, read_something();
}

My question is, can I execute writeTest from readTest?

To read something there must be something written. So I want to execute the writeTest (while being in test code of readTest) rather than repeating the codes of writeTest?

This is specially important when there is huge line of code in the writeTest.

Mocha test is not waiting for Publication/Subscription

Stack

Using Mocha + Velocity (0.5.3) for Meteor client-side integration tests. Let's assume that I have autopublish package installed.

Problem

If a document on the MongoDB was inserted from the server, the client-side mocha tests will not wait for the subscription to synchronise, causing the assertion to fail.

Code example

Server-side Accounts.onCreateUser hook:

Accounts.onCreateUser(function (options, user) {
  Profiles.insert({
    'userId': user._id,
    'profileName': options.username
  });

  return user;
});

Client-side Mocha Test:

beforeEach(function (done) {
  Accounts.createUser({
    'username'  : 'cucumber',
    'email'     : 'cucumber@cucumber.com',
    'password'  : 'cucumber' //encrypted automatically
  });

  Meteor.loginWithPassword('cucumber@cucumber.com', 'cucumber');
  Meteor.flush();
  done();
});

describe("Profile", function () {

  it("is created already when user sign up", function(){
    chai.assert.equal(Profiles.find({}).count(), 1);
  });

});

Question

How could I make Mocha wait for my profile document to make its way to the client avoiding the Mocha timeout (created from the server)?

JMeter save encrypted data in file

I have PreProcessor, where I have method to encrypt (AES) request data. Next I send that to server. How can I save bytes response before PostProcessor?

How to stub external interface in JEE6 application for testing?

I need to stub an external interface for testing in a JEE6 application. From the research I have done, it seems that there are 3 options

  1. Use an alternative
  2. Use @Specializes annotation
  3. Use Mockito

Which option is best to use?

Mock filesystem in ocaml

I am writing code that creates a folder/file structure in ocaml, and I want to write some tests for it. I'd like to not have to create and delete files each time the tests are run, since they cna be run many times.

What would be the best way to go to mock filesystem? I'd be open to have a filesystem in memory or just mock up functions.

cannot insert the username in to the field even though it is getting the id in selenium python

I am new to selenium. I want to test my site. I want to test with more than 100 clients. I have written this code. The strange part is that the password field is filling up but the username field is not filling up. The value is_displayed() is returning true but the data is not inserting into the field. Any help will be highly appreciated.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys 
import time
browser = webdriver.Firefox()
browser.get('http://ift.tt/1DDWbRg' )
print browser.current_url
for i in range(0,10):
    time.sleep(1)

username = browser.find_element_by_id("username" )
password = browser.find_element_by_id("password" )
submit   = browser.find_element_by_id("usernameButton")
a = username.is_displayed()
print a #prints true as it can find the id =username
username.send_keys("please god")
password.send_keys("display" )
submit.click()

Here is the HTML for it

<form id="username_form">
<div id="username_taken" class="alert alert-danger" role="alert">Sorry, that username is taken.</div>
<div class="form-group">
    <label for="uname" class="control-label">Username:</label>
    <br>
    <input type="text" class="form-control" placeholder="Enter your username."
    id="username">
    <br>
    <label for="password" class="control-label">Password:</label>
    <br>
    <input type="password" class="form-control" class="form-control" data-toggle="tooltip"
    data-placement="top" title="Please enter your password to unlock the contacts"
    placeholder="Enter your password (optional)" id="password">
    <br>
    <div class="togglebutton">
        <label>
            <input type="checkbox" id="private"> Allow my friends to find me. </label>
    </div>
</div>
<div class="modal-footer">
    <button id="usernameButton" type="button" class="btn btn-success">Submit</button>
</div>

How to handle a pop up using selenium webdriver

I'm working with a selenium webdriver to automate some process while attmepting to refresh a page , it is giving popup. On clicking of 'retry' button in that popup, page gets refreshed. I want to know how to handle this popup to click on 'retry' button.

I could not post the image as I'm not having enough reputation points.

How would you call the testing for the first time performed to the already released application?

App had been released with no testing. After the release, a tester was asked to perform a full test of the app: they meant to test as much as possible, trying to find all bugs (note, that no definite requirements were present). Not sure that it can be called full test or exhaustive test, since they are practically impossible. How would you call such testing activity?

mercredi 29 avril 2015

What kind of test is it?

First of all sorry for my english but I am from Italy.

I am reading "growing object-oriented software, guided by test" (Nat Pryce).

My question is: What kind of test he is talking about? Acceptance Test? End to End Test? System Test?

How to test the template of an Ionic modal?

I'd like to test the template of an Ionic modal. The problem is that I cannot access the template through the modal. I figured out a workaround and it works, but it must be other solution.

I solved this in the following way:

Created a mock Angular directive using the modal's template, because you can test a directive quite easily. Here is my test, using karma, mocha, chai and chai-jquery plugin:

'use strict';

describe('Directive: noteList', function () {
  var $compile;
  var scope;
  var mockDirective;

  angular.module('simpleNote').directive('mockNewNoteModal', function () {
    return {
      resrict: 'E',
      templateUrl: 'scripts/new-note/new-note-modal.html'
    };
  });

  beforeEach(module('simpleNote'));

  beforeEach(module('templates')); // module from ngHtml2JsPreprocessor karma task

   beforeEach(inject(function (_$compile_, _$rootScope_) {
     $compile = _$compile_;
     scope = _$rootScope_.$new();
     mockDirective = $compile('<mock-new-note-modal></mock-new-note-modal>')(scope);
     scope.$digest();
     angular.element(document).find('body').append(mockDirective); // for rendering css
  }));

  describe('Test the template of newNoteModal', function () {
    it('should have a class modal', function () {
      expect(mockDirective.find('div')).to.have.class('modal');
    });
  });
});

It would be great if you could test the modal straight. Or if it is not possible, is there any way to test any html template without creating a mock directive?

Sorry but I haven't had the 10 reputation to insert the links I'd like to, so I insert them as plain text:

karma: http://ift.tt/1cX2Gbq

mocha: http://ift.tt/1bVH9AJ

chai: chaijs.com/

chai-jquery: http://ift.tt/1rngKvQ

When more than one tests added to rest controller test why am I getting WebApplicationContext is required?

This is very funny. When I ran my controller test with more than one tests I am getting the following error when i run it with maven, but works fine in eclipse Junit.java.lang.IllegalArgumentException: WebApplicationContext is required at org.springframework.util.Assert.notNull(Assert.java:112) at org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder.<init>(DefaultMockMvcBuilder.java:43) at org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup(MockMvcBuilders.java:46) at com.akrilist.rest.web.akripost.controller.AbstractRestControllerTest.setup(AbstractRestControllerTest.java:32) at com.akrilist.rest.web.akripost.controller.AutoPostControllerTest.setup(AutoPostControllerTest.java:36) Then I ran one test commenting the other alternately (commented testA then run testB, then commented testB then run testA) both are passing. I have no idea what is happening when I put both of then are active tests. if any of you have clue please let me know. I have put my classes here.

AbstractRestControllerTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestRestServiceConfig.class, WebAppConfig.class })
@WebAppConfiguration
public abstract class AbstractRestControllerTest {
        protected MockMvc mockMvc;

    @Autowired
    protected WebApplicationContext webApplicationContext;

    /*@Inject
    protected UserAccountService userAccountServiceMock;*/

    @Before
    public void setup() {
       /* Mockito.reset(userAccountServiceMock);*/
        if(mockMvc == null) {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        }
    }
}

AutoPostControllerTest

public class AutoPostControllerTest extends AbstractRestControllerTest {

        @Autowired
        private AutoPostService autoPostServiceMock;
        @Autowired
        private AutoPostConverter autoPostConverterMock;

        @Before
        public void setup() {

                // Mockito.reset(autoPostServiceMock);
                // Mockito.reset(commentPostRepositoryMock);

                super.setup();
        }

        @Test
        public void testValidationErrorForNullProfileId() throws Exception {
                String description = TestUtil.createStringWithLength(501);
                AutoPost autoPost = new TestAutoPostBuilder().description(description).buildModel();
                mockMvc.perform(post("/auto/post").contentType(TestUtil.APPLICATION_JSON_UTF8).content(TestUtil.convertObjectToJsonBytes(autoPost))).andExpect(status().isBadRequest())
                                .andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
                                // .andExpect(jsonPath("$[]", hasSize(1)))
                                .andExpect(jsonPath("$.type", is("validation failure")));

                verifyZeroInteractions(autoPostServiceMock);
        }

        @Test
        public void testGet_shouldReturnPost() throws Exception {
                String description = TestUtil.createStringWithLength(501);
                String postId = TestUtil.createStringWithLength(16);
                Integer profileId = 123456;
                TestAutoPostBuilder testAutoPostBuilder = new TestAutoPostBuilder();
                AutoPost post = testAutoPostBuilder.postId(postId).description(description).profileId(profileId).buildModel();

                when(autoPostServiceMock.get(postId)).thenReturn(post);
                when(autoPostConverterMock.convertTo(post)).thenReturn(testAutoPostBuilder.buildDto());
                mockMvc.perform(get("/auto/post/" + postId).contentType(TestUtil.APPLICATION_JSON_UTF8)).andExpect(status().isOk()).andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
                                .andExpect(jsonPath("$.postId", is(postId))).andExpect(jsonPath("$.profileId", is(profileId))).andExpect(jsonPath("$.links", hasSize(1)));

                verify(autoPostServiceMock, times(1)).get(anyString());
                verifyNoMoreInteractions(autoPostServiceMock);
        }

}

Protractor: get url of not angular page

Case I try to test: On Angular app page press button, that redirects you to some other site (not an Angular app).

it('should go to 3d party  service when i click "auth" button' , function() {

    browser.driver.sleep(3000);
    element(by.id('files-services-icon')).click();
    element(by.id('box-vendor-menu-item')).click();
    browser.driver.sleep(2000);

    expect( browser.driver.getLocationAbsUrl()).toContain('http://ift.tt/1h2qJ45');
});

but I get:

UnknownError: unknown error: angular is not defined

How that can be achived? Thanks!

Can I run watir on Debian server in production

I have some parser controller. It using watir

class ParserController < ApplicationController
require 'open-uri'
require 'nokogiri'
require 'watir'
require 'selenium/webdriver'
def parse
 car_brands_count = CarBrand.count.to_i.to_i
 @output = Array.new
 browser = Watir::Browser.new
 browser.goto "http://www.site.ru/"
end

How rune this action with Watir in production with Debian server?

Using mock to patch a non-existing attribute

I'm trying to test a context manager that makes use of a class that uses some __getattr__ magic to resolve several attributes which don't actually exist on the class. I'm running into a problem where mock is raising an AttributeError when trying to patch the class.

Simplified example of objects I want to patch.

class MyClass(object):
    def __getattr__(self, attr):
        if attr == 'myfunc':
            return lambda:return None
        raise AttributeError('error')


class MyContextManager(object):
    def __init__(self):
        super(MyContextManager, self).__init__()
        self.myclass = MyClass()

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.myclass.myfunc()

Test code

def test_MyContextManager():
    with patch.object(MyClass, 'myfunc', return_value=None) as mock_obj:
        with MyContextManager():
             pass

    # Do some tests on mock object

Here is the error I get:

AttributeError: <class 'MyClass'> does not have the attribute 'myfunc'

I'm able to do this and run the test, but it doesn't restore the attribute (or simply remove the mock attribute in this case) automatically:

MyClass.myfunc= Mock(return_value=None)

I'm open to using another library besides mock to achieve this. I'm also using pytest.

getRequests() must return an Iterable of arrays

my code:

@RunWith(Parameterized.class)                                                                              
public class FreshResultCompareRunner2 {                                                                   


    //This is called before @BeforeClass !                                                                 
    @Parameterized.Parameters                                                                              
    public static Collection getRequests() throws IOException {                                            
        injector = Guice.createInjector(new MainModule());                                                 
        initStaticFromInjector();                                                                          
        initTestInput();                                                                                   
        return OrganizeTestParameterizedInput();                                                           
    }                                                                                                      


    private static void initTestInput() throws IOException {                                               

    }                                                                                                      

    private static Collection OrganizeTestParameterizedInput() {                                           

        Object[] objectMatrix = new Object[100];                                                
        for (int i = 0; i < 100; i++) {                                                         
            objectMatrix[i] = i;                                                                           
        }                                                                                                  
        return Arrays.asList(objectMatrix);                                                                
    }                                                                                                      

returns the following exception:

getRequests() must return an Iterable of arrays

how can i run the parameterized junit with increasing int only as input param?

say run the same test for i=0 ...100 ?

GeoLocation App not working on Android Emulator

I am testing a Geo-location App using an Emulator created in Android Studio. I have passed the latitude and longitude using DDMS which seems to work. I confirmed it by going to Google and checking the location. The location changes based on any changes on the Lat/Long. However, the App under test is not getting any location information. The App displays that the location services is not turned on when in fact it is turned on and working fine. Is there a specific command that can target the App on the emulator? I also have tried Geo fix commands but experiencing the same issue.

how to use parameterized junit when input is from several files?

I used to use Parameterized junit.

I have two files with a long list in each of them.

say

file_a
file_b

I loaded the two big lists into memory and compared each line in a different test.

Unfortunately the list grew too big and I had a memory problem to parse to parse it to json before saving to file.

That's why I split each long list to smaller files. say

file_a_1
file_a_2
file_a_3

and

file_b_1
file_b_2
file_b_3

how can I still use the parameterized junit infra and syntax to compare each corresponding list items, when each list is distributed to few files?

I have tried:

 @Test
    public void compareNewResponseToBaselineReturnsNoLargeDifferences() throws IOException {

        E2EResultShort baseLineList = routingResponseShortRepository.getBaseLine(chunkId);
        E2EResultShort freshRunList = routingResponseShortRepository.getLatestResponse(chunkId);


??? how do I iterate over differet `i` for each test ??

        List<String> testFailureMessages = alternativeShortTotalChecker.checkAllAlternativesShort(baseLine.get(i), freshRun.get(i));
        assertThat("testFailureMessages should be empty", String.join("", testFailureMessages), equalTo(""));
        assertThat("error messages should be null", freshRoutingResponse.regression_error, is(nullValue()));
    }

Rails Integration Test

I am taking a Rails class and am stuck on an Integration test. I have made a simple app that a user can use to share a link to a website. I want to create a test that will:

  1. Get the amount of links currently in the database
  2. Post a new link
  3. Check that the number of links has increased by 1.

Here is what I have so far:

test "posts new link and check count" do
   @link = Links.all
   get "/links/new"
   post_via_redirect "/links/new", :url => links(:test_link).url, :description => links(:test_link).description
   assert_equal '/links/new', path
   assert_difference("Link.count",n) do

I know this doesn't work but I cannot figure out the wording/syntax and would really appreciate a nod in the right direction. Please let me know if I should include other information.

Proxyquire can't find module

I'm trying to use proxyquire to mock dependency for testing. But I keep getting this error Cannot find module

I tried with full path and it's still complaining.

I have a src file which is in assets/js/src/lib and the test in js-tests/specs

Here's the code.

var proxyquire = require('proxyquireify')(require);
var stubs = { 
  'mandrill': { 
      Mandrill: function () { 
          return {
              messages : jasmine.createSpy('send')
          };
      }
  }
};

var jQuery = require('jquery'),
    Mandrill = proxyquire('../../assets/js/src/lib/Mandrill', stubs),
    globalMandrill = require('mandrill');

which I'm getting this error.

Error: Cannot find module '../../assets/js/src/lib/Mandrill' at

I'm using Grunt and PhantomJs to run the tests

Here's my Browserify in Gruntfile.js

browserify : {
    options: {
        preBundleCB: function(b) {
            b.plugin(remapify, [
                   // some module config

            ]);

        }
    },
    dist: {
        files : {
            // some files
        },
        options: {
            transform: ['browserify-shim']
        }
    },
    specs : {
        src : ['js-tests/specs/**/*.js'],
        dest : 'js-tests/build/specs.js',
        options: {
            transform: ["browserify-shim"]
        },
    }

},

Is it possible to click buttons on Android by ID via ADB?

I write a testing automation for some android application and i want to tap on application elements like buttons by their ID , i know that it can be done by writing an android test application and install it on device (like Espresso , UIAutomator , etc ...) , but i don't want to use this approach , so i ask if there anyway to do it from Android Debug Bridge ? Maybe someone know some sort of tool similar to monkey-runner that can perform it ? Basically what i ask - Is it possible to click buttons on Android by ID via ADB ??

Best way to do software testing in web2py [on hold]

I know maybe this is a dumb question but, what is the best way to do software testing in web2py? you know, for creating a test battery and run it whenever necessary instead of testing manually... If you can give me links to resources like tutorials of something it would be great. Thanks in advance.

Can't use DB Transactions in Controllers in laravel (DB::beginTransaction)

I have a DoctorsController which has a store method. I'm testing this method and I want my Models not to INSERT their data in testing environment. So I'm using DB::beginTransaction , DB::rollback() , DB::commit() methods in my controllers and my testing method to prevent INSERT queries. my problem is => Database is having records while my tests are running. I don't want any INSERTS during tests.

My test code :

public function testStoreMethod()
{
    /*
     * Test when validation fails
     */
    $data = include_once('DoctorsControllerFormData.php');

    foreach($data as $item){
        DB::beginTransaction();
        $response = $this->call('POST', 'doctors', $item);
        $this->assertResponseStatus(400, "response's HTTP code is not 400 : " . implode('\n',array_flatten($item)));
        Log::debug($response);
        DB::rollback();
    }
}

My DoctorsController code snippet : (which calls UsersController's store method)

public function store()
{
    //some code
    DB::beginTransaction();
    try{
        /*
         * User Creation
         */
        $user = new UsersController();
        $user->setResource('doctor');
        $userID = $user->store();

        //some other code
    }catch (InputValidationFailedException $e){
        DB::rollback();
        return Response::make(json_encode(array('error' => $e->getErrors())), \Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
    }catch(Exception $e){
        Log::error('Server Error at DoctorsController');
        DB::rollback();
        App::abort(500, $e->getMessage());
    }
}

My UsersController code snippet :

public function store()
{
    $user = new User;

    try{
        $inputs = Input::all();
        Log::info("input Data" . implode("\n", array_flatten(Input::all())));
        /*
         * User Creation
         */
        $v = Validator::make(
            $inputs,
            User::$rules
        );

        if($v->fails()) {
            Log::error('Validation Failed! ' . implode("\n", array_flatten($v->messages()->all())));
            throw new InputValidationFailedException($v);
        }
        $user->fname = Input::get('fname');//set first name
        $user->lname = Input::get('lname');//set last name
        $user->email = Input::get('email');//set email
        $user->cell = Input::get('cell');//set cell number
        $user->password = Hash::make(Input::get('password'));//set password
        $user->gender_id = Input::get('gender') == 'm' ? 1 : 0;//set gender
        $user->is_active = 0;//set activation status
        $user->role_id = ($this->resource == 'doctor') ? 1 : 2;
        $user->activation_time = 0;//set activation time default to 0
        $user->expiration_time = 0;//set expiration time default to 0
        //insert the user into DB
        $user->save();
    }catch (InputValidationFailedException $e){
        Log::info('User Validation Failed! ' . implode("\n", array_flatten($e->getErrors())));
        throw $e;
    }catch (Exception $e){
        Log::error('Server Error at UsersController!');
        throw $e;
    }

    return $user->id;
}

Thanks for your help.

AdColony Test Ads Undefined (Video Never Available) Unity

Using Unity3D

I have been trying to get adcolony ads to work in Unity for some time now. I have googled multiple things, have followed Adcolony's tutorials, and have even tried their example project. Yes I have changed my ZoneID and AppID in the script and have cnfigured it. yet, ads never work. Checking the Adcolony.StatusForZone always returnes "Unidentified". I have emailed AdColony support twice with no reply. Any help would be appreciated. Thanks.

Ads are set to Test Ads on Adcolony and they are turned to active.

Bash Scripting - Obtaining file names from directory

I am trying to create a zsh script to test my project. The teacher supplied us with some input files and expected output files. I need to diff the output files from myExecutable with the expected output files.

Question: Does $iF contain a string in the following code or some kind of bash reference to the file?

#!/bin/bash
inputFiles=~/project/tests/input/*
outputFiles=~/project/tests/output

for iF in $inputFiles
./myExecutable $iF > $outputFiles/$iF.out
done

Note:

Any tips in fulfilling my objectives would be nice. I am new to shell scripting and I am using the following websites to quickly write the script (since I have to focus on the project development and not wasting time on extra stuff):

Grammar for bash language

Begginer guide for bash

Codeception click input radio

on my website i'm starting to use codeception to perform the tests. On a page i have a form that has some fields to fill with data to perform the email test content. The problem is that this form have some input type radio. This inputs are inside on a div. On the end of this post will give the example to get a better perception of my problem. My problem is that i can't check this input. I had tried to used checkOption, selectOption, click functions and they simply don't work. Here is some html:

http://ift.tt/1PXKj5w

How can i solve this?

FactoryGirl - can't write unknown attribute, and undefined method `name'

I'm trying to create a photo factory that's in a many to one association with gallery. And I'm getting two errors, depending on how I specify the association between those two models.

Here's the models:

Photo

belongs_to :gallery, class_name: "SevenGallery::Gallery"

Gallery

has_many :photos, class_name: "SevenGallery::Photo", foreign_key: "seven_gallery_gallery_id", dependent: :destroy

And the migrations

create_table :seven_gallery_galleries do |t|
   t.string :title  
   t.timestamps null: false
 end

create_table :seven_gallery_photos do |t|
   t.string :caption
   t.string :image
   t.references :seven_gallery_gallery, index: true
   t.timestamps null: false
 end

 add_foreign_key :seven_gallery_photos, :seven_gallery_galleries, on_delete: :cascade

Now Here's my factories: Gallery:

FactoryGirl.define do
  factory :gallery, class: 'SevenGallery::Gallery' do
    title "an event gallery"
    factory :gallery_with_photos do 
        after(:build) do |gallery| 
            gallery.photos << FactoryGirl.create(:photo_one, seven_gallery_gallery_id: gallery)
            gallery.photos << FactoryGirl.create(:photo_two, seven_gallery_gallery_id: gallery)
            gallery.photos << FactoryGirl.create(:photo_three, seven_gallery_gallery_id: gallery)
        end
    end
  end
end

And Photo:

FactoryGirl.define do
  factory :photo, class: "SevenGallery::Photo" do

      factory :photo_one do
      end

      factory :photo_two do
      end

      factory :photo_three do
      end

      factory :photo_with_gallery do
        gallery 
      end
  end
end

And here's the controller spec that generates the error:

it "changes is_main to true in self and false in rest" do
    photo_one = FactoryGirl.create(:photo_with_gallery)
    expect(photo_one.gallery).to be_a SevenGallery::Gallery
end

Whenever I run the test I get this error:

Failure/Error: photo_one = FactoryGirl.create(:photo_with_gallery)
     ActiveModel::MissingAttributeError:
       can't write unknown attribute `gallery_id`
     # ./spec/controllers/seven_gallery/photos_controller_spec.rb:

When I change the association part to be:

factory :photo_with_gallery do
  association :gallery, factory: gallery    
end

I get this error:

Failure/Error: photo_one = FactoryGirl.create(:photo_with_gallery)
  NoMethodError:
     undefined method `name' for :photo_with_gallery:Symbol 
   # ./spec/controllers/seven_gallery/photos_controller_spec.rb:8

Any help would ne appreciated. Thanks.

Kotlin and new ActivityTestRule : The @Rule must be public

I'm trying to make UI test for my android app in Kotlin. Since the new system using ActivityTestRule, I can't make it work: it compiles correctly, and at runtime, I get:

java.lang.Exception: The @Rule 'mActivityRule' must be public.
at org.junit.internal.runners.rules.RuleFieldValidator.addError(RuleFieldValidator.java:90)
at org.junit.internal.runners.rules.RuleFieldValidator.validatePublic(RuleFieldValidator.java:67)
at org.junit.internal.runners.rules.RuleFieldValidator.validateField(RuleFieldValidator.java:55)
at org.junit.internal.runners.rules.RuleFieldValidator.validate(RuleFieldValidator.java:50)
at org.junit.runners.BlockJUnit4ClassRunner.validateFields(BlockJUnit4ClassRunner.java:170)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:344)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:74)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55)
at android.support.test.internal.runner.junit4.AndroidJUnit4ClassRunner.<init>(AndroidJUnit4ClassRunner.java:38)
at android.support.test.runner.AndroidJUnit4.<init>(AndroidJUnit4.java:36)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.support.test.internal.runner.junit4.AndroidAnnotatedBuilder.buildAndroidRunner(AndroidAnnotatedBuilder.java:57)
at android.support.test.internal.runner.junit4.AndroidAnnotatedBuilder.runnerForClass(AndroidAnnotatedBuilder.java:45)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runner.Computer.getRunner(Computer.java:38)
at org.junit.runner.Computer$1.runnerForClass(Computer.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:98)
at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:84)
at org.junit.runners.Suite.<init>(Suite.java:79)
at org.junit.runner.Computer.getSuite(Computer.java:26)
at android.support.test.internal.runner.TestRequestBuilder.classes(TestRequestBuilder.java:691)
at android.support.test.internal.runner.TestRequestBuilder.build(TestRequestBuilder.java:654)
at android.support.test.runner.AndroidJUnitRunner.buildRequest(AndroidJUnitRunner.java:329)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:226)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1584)

Here is how I declared mActivityRule:

RunWith(javaClass<AndroidJUnit4>())
LargeTest
public class RadisTest {

    Rule
    public val mActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule(javaClass<MainActivity>())

   ...
}

It is already public :/

Unit testing using Eclipse - JUNIT

I wrote an android application that uses GPS mainly, using Eclipse.

I want to do a JUNIT test for the application.

I have searched the internet but I still don't understand. please help me.

How do I test my methods, such as saving coordinates or finding coordinates...etc.

My main activity has only one click button that takes the user to location services page... how is that all tested?

Mockito: When a mock Object's void method is called, use a real Object's void method instead

I want to do this:

when(GridLayout.class).addComponent(Matchers.any(Component.class), Matchers.anyInt(), Matchers.anyInt()).thenUseInstead(realLayout.addComponent(...));

Where GridLayout is my mock object and realLayout is a real Layout object.

I spotted doAnswer in the MockitoAPI (I think thats what I want?) however I am struggling to put it all together.

MockitoAPI 'doAnswer' example:

  doAnswer(new Answer() {
      public Object answer(InvocationOnMock invocation) {
          Object[] args = invocation.getArguments();
          Mock mock = invocation.getMock();
          return null;
      }})
  .when(mock).someMethod();

Can anyone help?

How to include JUnit tests in SONAR analysis

I'm using sonarqube-5.0.1 to manage code quality and maven as build tool. when i run mvn sonar:sonar it doesn't consider the test classes for analysis. How can i include test classes to be analysed in sonar.

my pom.xml is given below

<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
<modelVersion>X.X.X</modelVersion>
<groupId>com.XXXXXX.XXXXX</groupId>
<artifactId>XXXX-XXXXXX</artifactId>
<version>X.X.X</version>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <slf4j.version>1.6.1</slf4j.version>
    <suiteXmlFile>src/test/resources/junit.xml</suiteXmlFile>
    <maven.source.classifier>src</maven.source.classifier>
    <maven.source.test.classifier>tests-src</maven.source.test.classifier>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.18.1</version>
            <configuration>
                <suiteXmlFiles>
                    <suiteXmlFile>${suiteXmlFile}</suiteXmlFile>
                </suiteXmlFiles>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-project-info-reports-plugin</artifactId>
            <version>2.7</version>              
        </plugin>

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>cobertura-maven-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <formats>
                    <format>html</format>
                    <format>xml</format>
                </formats>
            </configuration>
        </plugin>

        <!-- Make Jars -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <excludes>
                    <exclude>**/*.properties</exclude>
                    <exclude>**/*.txt</exclude>
                    <exclude>**/*.xml</exclude>
                    <exclude>**/*.xsd</exclude>
                    <exclude>**/*schema*</exclude>
                </excludes>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>dependency-jars/</classpathPrefix>
                    </manifest>
                    <addMavenDescriptor>false</addMavenDescriptor>
                </archive>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>jar</goal>
                        <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <!-- Make Source jar -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-source-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <excludes>
                    <exclude>**/*.properties</exclude>
                    <exclude>**/*.txt</exclude>
                    <exclude>**/*.xml</exclude>
                    <exclude>**/*.xsd</exclude>
                    <exclude>**/*schema*</exclude>
                </excludes>
                <includePom>true</includePom>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>jar</goal>
                        <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <!-- Make Source Javadocs -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>2.10.2</version>
            <configuration>
              <show>private</show>
              <reportOutputDirectory>${project.basedir}/docs</reportOutputDirectory>
            </configuration>
        </plugin>
    </plugins>
</build>
<!-- Generate Reports Summary Note: dependency management reports are excluded-->
<reporting>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-project-info-reports-plugin</artifactId>
            <version>2.7</version>
            <configuration>
                <dependencyDetailsEnabled>false</dependencyDetailsEnabled>
                <dependencyLocationsEnabled>false</dependencyLocationsEnabled>
            </configuration>
            <reportSets>
                <reportSet>
                    <reports>
                        <report>cim</report>
                        <report>distribution-management</report>
                        <report>index</report>
                        <report>issue-tracking</report>
                        <report>license</report>
                        <report>mailing-list</report>
                        <report>modules</report>
                        <report>plugin-management</report>
                        <report>plugins</report>
                        <report>project-team</report>
                        <report>scm</report>
                        <report>summary</report>
                    </reports>
                </reportSet>
            </reportSets>
        </plugin>
    </plugins>
</reporting>
<dependencies>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.6.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-hdfs</artifactId>
        <version>2.6.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-hadoop-compat</artifactId>
        <version>0.98.9-hadoop2</version>
        <type>test-jar</type>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-hadoop2-compat</artifactId>
        <version>0.98.9-hadoop2</version>
        <type>test-jar</type>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-server</artifactId>
        <version>0.98.9-hadoop2</version>
        <type>test-jar</type>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-common</artifactId>
        <version>0.98.9-hadoop2</version>
        <type>test-jar</type>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-server</artifactId>
        <type>jar</type>
        <version>0.98.9-hadoop2</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-client</artifactId>
        <version>0.98.9-hadoop2</version>
    </dependency>
    <dependency>
        <groupId>jdk.tools</groupId>
        <artifactId>jdk.tools</artifactId>
        <systemPath>${env.JAVA_HOME}/lib/tools.jar</systemPath>
        <scope>system</scope>
        <version>1.7</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

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

    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>1.6.2</version>
    </dependency>

    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>1.6.2</version>
    </dependency>
</dependencies>

Javascript Jasmine Testing: Prevent tested function to call function from object that was created within tested function

I want to test a Javascript function with Jasmine that has a structure like this:

showEditUser: function (...) {
    // more code here...
    var editUserView = new EditUserView();
    // more code here...
    editUserView.generate(...);
}

editUserView.generate() causes an error. That does not matter because I don't want to test it. But how can I prevent it from being called?

EditUserView is a RequireJS Module that extends another Module called BaseView. The function generate() is defined in BaseView. There are other Modules that extend BaseView and I want all of them not to call generate while testing. How can I do that with Jasmine? It seems not to be possible with spyOn(...).and.callFake() because I don't have the editUserView Object when calling the function. Is there kind of a static way to tell Jasmine to callFake() the function generate in BaseView?

Test plan for reporting system

I have a software suite that consists of multiple integrated software packages. They all run off of a single centralised SQL database.

We are in the stage where we are writing test plans and have allocated a single test plan for each independent module of the software. The only one left to write is the test plan for the reporting module. This particular module does nothing but run reports on the data in the SQL database (which will be written by the other modules).

Any testing iterations are preceded by developer, regression and integration testing, which should remove any issues of the database data not being correctly maintained.

My dilemma is how to approach the black box test plan for the reporting module. The way I see it there are three options:

  • Append the reporting test cases to the test plans for the modules that influence them (downside: the modules work together to produce the reports; reports cannot be divided up by module like that)
  • Write a test plan for reporting with specified pre-requisites, that are essentially a list of instructions of tasks to perform in the other modules, followed by test cases to test that the reporting is producing correctly in response to these tasks (downside: very complicated and long-winded)
  • Write a test plan for reporting with set datasets on a dedicated controlled SQL database (downside: lack of flexibility)

It looks to me that the second option is the best. It's the longest-winded but that alone is hardly a reason to discount something.

Does anyone have any experience with testing a module purely for reporting, who can hopefully provide an insight into the best / industry-standard ways to do this?

Thanks in advance!

Automatic Testing of socket using jasmine

Currently, I am using frisby Testing framework in my project to test API End-points which using jasmine-node. now I am using sockets.io in my project for notification between client/server and it is working fine. How can I test socket.io integration/implementation with jasmine-node (without using mocha)? Any suggestion will be appreciated.

Appium - running browser tests without clearing browser data

I'm testing a web application on Chrome using Appium. Whenever I launch a test, all browser data (bookmarks, history etc.) is deleted. Is there any way to stop this from happening?

I tried setting the noReset capability to true, but that didn't help.

Thank you in advance for any help

android how to send a system broadcast

I am working with testing android app's power consumption and to make the app consump most power as possible,I want to send a system broadcast like "android.intent.action.PACKAGE_ADD",but the system reboot when I send it by adb shell am broadcast command.

So is there any method to send a system broadcast?

Tests with CUNIT - walkthrough analysis / code coverage

I want to test some code with CUnit. Does anyone know if it is possible to do a walktrough Analysis?

I want to have something, that says, you`ve tested 80% of your function.

It must be ensured, that 100% coverage are reached with the test.

mardi 28 avril 2015

configuration error PKG_CHECK_MODULES(CHECK,check>=0.9.6) for check framework in ubuntu

I install check-0.9.9 UI(unit testing) framework and trying to configure and execute example test case which is given with check setup but while configuring I am getting this issue. PKG_CHECK_MODULES(CHECK,check>=0.9.6)

I also followed README provided by this example.you can find this example source in following path check0.9.9/doc/examples.

Disable functional and acceptance test in Yii2

I'm starting using codeception in Yii2 to perform unit tests, functional tests and acceptance tests.

I would focus on the unit tests for the moment.

So, I looking for the appropriate way to disable functional tests and acceptance tests without deleting my existing tests files.

I want to create bat file, The Selenium Project is been developed using TESTNG and Java. I have suite in xml.

Now i want to create bat file, Please file in creating bat file.

I don't have main function in my project.

I want to run the test suite in Main class. How can i do that ? Source code please.

How can I integrate Selenium with the Perfecto tool for Automation Testing?

I was trying to integrate selenium with the Perfecto tool for mobile app testing (automation). I do know that there is a plugin that I can use to integrate them. But I want to know the specific javascripts used for the integration.

Lost trying to make the rspec test pass

I have this class:

class Zombie < ActiveRecord::Base
  attr_accessible :iq
  validates :name, presence: true

  def genius?
    iq >= 3
  end

  def self.genius
    where("iq >= ?", 3)
  end
end

And I am making the rspec test:

describe Zombie do
  context "with high iq" do
     let!(:zombie) { Zombie.new(iq: 3, name: 'Anna') }
     subject { zombie }

     it "should be returned with genius" do
       should be_genius
     end

     it "should have a genius count of 1" do
       Zombie.genius.count.should == 1 
     end
  end
end

I am having this error message:

Failures:

1) Zombie with high iq should have a genius count of 1
Failure/Error: Zombie.genius.count.should == 1
expected: 1
got: 0 (using ==)
# zombie_spec.rb:11:in `block (3 levels) '

Finished in 0.2138 seconds
2 examples, 1 failure

Failed examples:

rspec zombie_spec.rb:10 # Zombie with high iq should have a genius count of 1 

I am using the syntax: let!(:zombie){...} but it is telling that got 0 when I expected 1. Any idea? Maybe I have passed a lot of time looking to this code and I don't see where is the problem.

Why do we write test cases?

So I know you might say, this is not a good question and a simple search can give me my answer, but it is not true. I have read a lot about testing and its importance. I know writing test cases helps to find the potential errors while programming. Also when you read the books they all are just repeating the same abstract definition. But after writing a lot of test cases, I came to this conclusion that it is not that much helpful neither preventing the potential errors nor increasing the product quality.

So just imagine we have a test case as below over a bunch of our functions:

Assert.IsTrue(divideNumbers(4,3) == 1);
Assert.IsTrue(divideNumbers(4,2) == 2);
Assert.AreEqual(divideNumbers(8, 4), 2);
Assert.That(divide(10,2), Eq(5))

So, while writing a test case, normally we are trying to assert the truthfulness of a bunch of very basic issues like Are two equations true? Is the result of this function equal to a desired result? Are they equal? Does it fail? Is an object an instance of a specified class?,.......

I have worked in a lot of software development teams. Almost in all the times and in all the teams, after writing some test cases we encounter a situation where we see the functions of Assert Class can't help us since they are very basic while the errors normally raises in a specific situations that are not a matter of being true, being equal, not being null,....

So, why do really write test cases? Why we really need them and how they can help us increasing the product quality and decreasing the potential errors?

Android Studio Espresso Testing Error: Empty Test Suite

I keep running into the following error when trying to execute my tests in Android Studio: Test running failed: Unable to find instrumentation info for: ComponentInfo{.test/android.support.test.runner.AndroidJUnitRunner}

My test class is in the androidTest/java directory and has a constructor. My build.gradle is correct too. Any help is appreciated.

Test Class

@RunWith(AndroidJUnit4.class)
@LargeTest
public class AndroidUITests extends ActivityInstrumentationTestCase2<UserActivity>{

    private UserActivity userActivity;

    public AndroidUITests() {
        super(UserActivity.class);
    }


    @Before
    public void setUp() throws Exception {
        super.setUp();
        injectInstrumentation(InstrumentationRegistry.getInstrumentation());
        userActivity = getActivity();
    }

    @Test
    public void testPhoneIconIsDisplayed() {
        // When the phone_icon view is available,
        // check that it is displayed.
        onView(ViewMatchers.withId(R.id.groupCreate)).perform(click())
                .check(matches(withText("Enter a name")));
    }
}

app/build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        testInstrumentationRunner
        "android.support.test.runner.AndroidJUnitRunner"
    }

    packagingOptions {
        exclude 'LICENSE.txt'
    }
}

dependencies {
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'
    androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
}

Determine if a java execution from another java application was done successfully

I have an application that calls a java test class in a specified location of my PC. The path is hard-coded for now, and I checked that it worked by executing it from the command line (in case you want to see it: java -cp C:\Users\user\Documents\workspace\test\build\test.jar org.junit.runner.JUnitCore us.test.DynamicWebserviceInvocationTest), so I know that the command works fine.

The thing is, when I do Runtime.getRuntime().exec(command), if I try to log the resulting InputStream and ErrorStream of its resulting process, the program stucks. I tried with exitValue() and waitFor(), but the first throws an incompletition error and the second also gets stuck. The weird thing is that if I don't touch anything of this (the streams, or using the functions), the program has no problem ending.

So my question is: Why could this be? The next step is to build the command with given parameters, but if I can't see the resulting inputs I can't be completely sure if the tests are running or not.

The code, in case you want to see it:

Runtime runtime=Runtime.getRuntime(); logger.debug("Attempting to execute the test {} at path {}",classpath,applicationLocation);

        String command="java -cp C:\\Users\\user\\Documents\\workspace\\test\\build\\test.jar org.junit.runner.JUnitCore us.test.DynamicWebserviceInvocationTest";
        Process process=runtime.exec(command);
        BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(process.getInputStream()));

        BufferedReader stdError = new BufferedReader(new 
             InputStreamReader(process.getErrorStream()));

        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }

Cloning element finders

While researching available ElementFinder and ElementArrayFinder methods, I've noticed that there is a clone() method which is briefly documented:

Create a shallow copy of ElementFinder.

From what I understand, clone() is not coming from WebdriverJS and is a protractor-specific function. What I don't understand is why would you want to clone an element finder or an element finder "array" in your tests? What use cases does clone() cover?


I've looked into the protractor source code to find example usages, but found only the underlying change set, which didn't help to have a clear picture.

Error while waiting for the protractor to sync with the page: "Cannot read property 'get' of undefined"

My test target page has SSO integrated login. Once I hit the page, SSO integrated windows authentication will occur then directed to home page.

I tried to turn Sync off and it works for first test to check title but for second test, it will return error unable to locate element and when I turn on Sync, it will return out of sync error and undefined error.

describe('Test area to ', function () {

var menuObjects = require('../page/MenuObjects.js');

it('Verify Page Title', function () {
    menuObjects.setSyncOff(); 
    browser.get('/home/');
    expect(browser.getTitle()).toEqual('Home');
    browser.driver.sleep(3000);
});

it('Navigate ', function () {
    menuObjects.setSyncOn();
    menuObjects.menuButton.click();        
});
});

Error message for Navigate - with menuObjects.setSyncOn();

Error while waiting for Protractor to sync with the page: "Cannot read property 'get' of undefined"

Error message for Navigate - with menuObjects.setSyncOff();

NoSuchElementError: No element found using locator: By.id("menu-link")

ng-app is included in div within body:

<body style="width: 100%">
<div class="frame" style="width: 100%">
    <div class="container-fluid" style="width: 100%">
        <div class="" style="width: 100%">
            <div style="width: 100%">
                <!--_AngularBaseLayout: BEGIN-->                    

<div ng-app="myHomeApp" ng-cloak class="ng-cloak">

Any suggestion?

How to change URL in protractor

I'm wondering how do you change the current URL upon pressing some button or link.

browser.waitForAngular();
expect(browser.driver.getCurrentUrl()).to.eventually.match(/document/).and.notify(callback);

I know this code will get the url and match it with document, I would like to set the URL upon a click.

e.g. I'm on Facebook and I want to go to profile, I click Profile button but want to update the URL by parsing a string value to it rather than a class/function

As I have a piece of code that doesn't have any classes to point to, the only thing I have is a href which contains the path location to the page.

How can I use protractor to verify an URL?

I would like to get the current URL using protractor, and then verify that this URL is the one that I need. I am using:

istheSameURL(url) {
    return browser.getCurrentUrl() === 'http://localhost:9000/#/analysis/62/1';
}

However, it is not working.

USing the Visual Studi test framework for system tests

I'm new to Visual Studio and its unit test framework and I'm unsure if it is suitable for what I would call system tests.

I have a C++/CLI class with a few methods that look something like this:

double ReadValue(int command);
void WriteValue(int command, double value);

These methods communicate with an embedded system, which is what I'm actually interested in testing. I would like to test that I can read and write to registers and that I receive error codes when values are out of range and so on.

My question is, is it wrong to use unit tests, and specifically the Visual Studio testing tools, when I'm not actually interested in testing the Read/Write methods themselves?

Why Spring @Qualifier does not work with Spock and Spring Boot

I'm trying to write a test for controller in the Spock.

@ContextConfiguration(loader = SpringApplicationContextLoader.class,
    classes = [Application.class, CreateUserControllerTest.class])
@WebAppConfiguration
@Configuration
class CreateUserControllerTest extends Specification {

    @Autowired
    @Qualifier("ble")
    PasswordEncryptor passwordEncryptor

    @Autowired
    UserRepository userRepository

    @Autowired
    WebApplicationContext context

    @Autowired
    CreateUserController testedInstance

    def "Injection works"() {
        expect:
        testedInstance instanceof CreateUserController
        userRepository != null
    }

    @Bean
    public UserRepository userRepository() {
        return Mock(UserRepository.class)
    }

    @Bean(name = "ble")
    PasswordEncryptor passwordEncryptor() {
        return Mock(PasswordEncryptor)
    }

}

Application class is just Spring Boot simplest config (enables autoscanning).It provides a with PasswordEncryptor. I want to replace this bean from Application with my bean providing a mock.

But unfortunately Spring throws a NoUniqueBeanDefinitionException:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.jasypt.util.password.PasswordEncryptor] is defined: expected single matching bean but found 2: provide,ble
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 54 more

@Qualifier annotation seems not working at all. What can I do?

How to test API client using mocks really works

I made an API client (a custom Django Auth Backend) that integrates with a company authentication API.

I used Responses to mock out the API as this offered many benefits, fast tests, works with our CI, isolated etc etc, and the result has been great so far.

The real question though is does my client really work?

I was thinking of spinning up a test instance of the API mentioned and then running my tests against that. It would be more painful as I would have to write scripts to restore the db to a known state etc. and it probably wouldn't work with our CI (Codeship), but at least I would have confidence things work as intended.

Then I would have to somehow toggle on and off Responses to be able to do this.

What are some simple ways of solving this problem?

Junit testing a class which extends WizardPage

I am tasked with trying to create a Junit test suite of a class which extends 'WizardPage'.

  public class PageDataModel extends WizardPage

Every time I try and create an object of this class within my test suit, the value of the page is null. Below is an example of a test I'm trying to execute.

    @Test
public void testEntityNameNotNumber() {
    PageDataModel pageDataModel = new PageDataModel("testing"); 
    pageDataModel.setContents("person");        
    String temp = pageDataModel.getContents();      
    assertEquals("person",temp );
}

Could someone please suggest where I'm wrong. Many thanks.

casper.js: Switch popup ("tab") permanently

so my Situation is: I use casperjs 1.1.x (latest dl-version from page) together with phantomjs 1.9.8 on a windows os.

To make a long story short, my Problem in one sentence: I'm in need to switch my page permanently, for I have an "entrypage" where I add an ID and click a link which opens the app-page in a new tab via target=_blank.

I am aware of waitForPopup and withPopup-functions of casperjs, but sadly the withPopup-function changes the page back after one call.

this is my so-far test-scenario:

casper.test.begin('My Testsuite', function(test) {
casper.options.waitTimeout = 15000;
casper.start('http://myAppEntryPage/', function() {
    test.assertUrlMatch(/myAppEntryPage/, 'Casper starts on myAppEntryPage');  
    test.assertExists("#HyperLink1", 'Button -xxx- exists');
    test.assertExists("#HyperLink2", 'Button  -yyy- exists');
    test.assertExists("#TextBox1", 'Input  for zzz exists. Ready to go! \n\n');
})

casper.then(function(){
    this.sendKeys('input#TextBox1', '124733');
}).then(function(){
    this.test.assertField('TextBox1', '124733');
}).then(function(){
    this.click('#HyperLink2');
}).waitForPopup('http://myApp/configurator.aspx#Id=124733', function() {
    this.test.assertEquals(this.popups.length, 1);
}).withPopup('http://myApp/configurator.aspx#Id=124733', function() {
    this.test.assertTitle('Title2');
    //this.page = this.popups[1];
    console.log('Successfully changed to view! ' + this.getCurrentUrl());
}).waitForSelector('.list-weekdays', function(){ 
    //this is not working because I am in http://myAppEntryPage again.
    this.test.assertExists('.list-weekdays-day');
    console.log('App-Mainview loaded. Lines appearing.\n\n')
});

casper.run(function() {
    test.done();
    exit(0);
})
});

So as the comment above states, I am at http://myAppEntryPage instead of http://myApp/configurator.aspx#Id=124733 - the "popup" I want to be and work with for the rest of my Testsuite.

I just tried this:

this.page = this.popups[1];

inside of the withPopup-function, but this leads to an exception, so I am out of Ideas for now and hope you could help me out.

The relevant Part of the Output of my test-console is:

Successfully changed to Wochenansicht! http://myApp/configurator.aspx#Id=124733
FAIL ".list-weekdays" still did not exist in 15000ms
#    type: uncaughtError
#    file: testsuite.js
#    error: ".list-weekdays" still did not exist in 15000ms

#    stack: not provided
FAIL 8 tests executed in 18.525s, 7 passed, 1 failed, 0 dubious, 0 skipped.

So I think I am simply at the wrong page. I also tried to find other elements in the resulting main-page, especially higher in the dom-hierarchy, but with no luck.

So: Is there a way to permanently change the popup?

Would be great to hear from you!

Best regards, Dominik

Any ideas regarding placing a timer in a jsp - servlet based online examination

I want to develop and design an online examination system with result analysis , so i need some help from the enthusiastic Java Programmers , hope i get best out of your help :) Thanks in advance .

Edit ui-grid cell value using protractor

I am using protractor to test angular ui-grid 3.0. All cells in grid are editable. In my tests I can get cell using following method:

dataCell: function( gridId, fetchRow, fetchCol ) {
    var row = this.getGrid( gridId ).element(by.css('.ui-grid-render-container-body')).element( by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index').row( fetchRow )  );
    return row.element( by.repeater('(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name').row( fetchCol ));
}

from http://ift.tt/1IiwpZx.

After I get first cell from first row, when I try to send value to cell

cell.click();
cell.sendKeys("newCellValue");

test breaks. I get following error message:

    - Failed: unknown error: cannot focus element.

The problem occurs when sendKeys method is called. Does anyone know the correct way to change cell value using protractor?

FsCheck model based testing with timed behaviour

Is there a possibility to model timed behavior so that fscheck's

 Check.Quick(asProperty spec)

generate test cases for it?

Example: There are 3 States: A, B and C
if state B is activated the system switches after X seconds automatically to state C if no other user input (e.g. switch to state A) occurs.

http://ift.tt/1b9cpe9

So fscheck should automatically wait for this X seconds and check then if the system is in the correct state.

Testing svg charts in Watir-webdriver

I am trying test if a chart has the correct title of 'Revenue'. I am using watir-webdriver to automate these test. Can anyone help?

HTML code:

<nvd3-multi-bar-chart data="chartData" id="revenueChart" class="chart-render ng-isolate-scope" showxaxis="true" showyaxis="true" color="colorFunction()" interactive="true" xaxistickformat="xAxisTickFormat()" yaxistickformat="yAxisTickFormat()" yaxisshowmaxmin="false" callback="chartCreatedCallbackFunction()" nodata="">

<text x="20" y="20" text-anchor="start" class="statistics-title">Revenue</text>

<text x="20" y="40" text-anchor="start" class="statistics-title-total">Total: 1,222,140 USD</text>

All i could come up with is this:

if @browser.div(:xpath, '//*[@id="revenueChart"]/svg/text[1]').class == 'Revenue'
    print_green('Revenue Chart title           --- Pass')

end

ExtJS 4 Siesta. Testing my own application ui

I'm trying to test one of my view which consists of form and grid inside this form. I created a Harness file and named it index.js. I also created the index.html file with all needed paths to extjs and siesta as well. To be short I repeated all movements from 'Siesta getting started guide'. But now, when I created a test file and put this code inside:

// also supports: startTest(function(t) {
StartTest(function(t) {
    var grid = Ext.create('MyApp.view.ChannelForm', {
        renderTo : Ext.getBody(),
    });
})    

I received this error:

Test threw an exception

TypeError: c is not a constructor

I consider it is because of Siesta doesn't see my app. Do you have any thoughts about this case?