mardi 31 juillet 2018

Do you know the best cloudy testing service from test in?

please check https://www.testin.net/ first, I know most of app developers are all worrying about their app's performance and bugs detection before publishing, and also does it fit all target devices and network, these are all not clear with few testers' working. and I know Testin is really a professional company providing app testing services with real mobile devices under the localized real network.and lately it will add more testing services for all app developers&owners.

How to test test Web Services with Elixir?

We have a couple of REST APIs that need to be tested. APIs are owned by some other team. Currently, we use Node.js with Ava to test our external API.

We have recently started exploring Elixir as our scripting language. We would like to experiment with Elixir to test REST API. The question here is - how to test external web services/REST API with Elixir?

Every Google search around Elixir testing refers back to ExUnit which is basically for unit testing of Elixir apps. We don't have any app written in Elixir or in Phoenix.

All we want to do is to test API end-to-end. How to do that with Elixir? Which libraries to use? I know I can make network calls from my tests written in ExUnit and verify the API behavior, but not sure if it is the right way.

NOTE: We already have JMeter in place for load testing of API but we wish to keep functional testing separate from load testing due to complex workflows involved with API.

DRY double in RSpec

How to DRY(don't repeat yourself) the double in RSpec? For example:

let(:s1) {instance_double(Class1,
                            :attr1 => val1
                            :attr2 => val2
                            :attr3 => val3
                            :attr4 => val4
                            :attr5 => val5)}


let(:s2) {instance_double(Class1,
                            :attr1 => val0 # the only difference between s2 and s1
                            :attr2 => val2
                            :attr3 => val3
                            :attr4 => val4
                            :attr5 => val5)}

let(:s3) {instance_double(Class1,
                            :attr1 => val6 # the only difference between s3 and s1
                            :attr2 => val2
                            :attr3 => val3
                            :attr4 => val4
                            :attr5 => val5)}

These 3 doubles are very similar and it seems we can refactor. But I tried:

  1. to make a basic hash for them:

    basic_hash = {attr2 => val2, attr3 => val3, attr4 => val4, attr5 => val5}

And then modified this basic hash and pass it into instance_double, for example, pass it into :s1:

basic_hash_s1 = basic_hash.clone
basic_hash_s1[:attr1] = val1
let(:s3) {instance_double(Class1, basic_hash_s1)

But this doesn't work. I'm working on an existing project and the Rspec didn't give any error message(maybe the project has some setting?), it just jumped the whole spec file.

  1. I also tried to allow on double:

    allow(s1).to receive(:attr).and_return(val1)

It still doesn't work.

Somebody know how to refactor this? Thanks!

How to get coverage for multiple files in GOLANG

I have a package in GO-LANG that has several files implementing it. (all files are in the same directory)

file1: mypackage.go
package mypackage
func f1 () {}

file2: mypackage_addition.go
package mypackage
func f2 () {}

file3: mypackage_test.go
package mypackage
import "testing"
func TestF1 (t *testing.T) { 
    f1()
}

file4: mypackageAddition_test.go
package mypackage
import "testing"
func TestF2 (t *testing.T) { 
    f2()
}

I do this in order to get coverage:

mypackage> $ tree
.
├── mypackage.go
├── mypackageAddition_test.go
├── mypackageAdditions.go
└── mypackage_test.go

0 directories, 4 files
mypackage> $ go test -v -coverprofile cover.out ./...
=== RUN   TestF2
--- PASS: TestF2 (0.00s)
=== RUN   TestF1
--- PASS: TestF1 (0.00s)
PASS
coverage: 0.0% of statements
ok      github.com/MyDevelopment/mypackage  0.701s  coverage: 0.0% of statements
mypackage> $ go tool cover -html=cover.out -o cover.html
mypackage> $ open cover.html 

enter image description here enter image description here

When I open the html, I only get coverage for f1().
f2 is called (I verified it in debug), and the run of f2 is represented in the text, but not in the html file.

Any help is appreciated.

Testbench in verilog produces errors saying LOC constraints are invalid

When I run my testbench, it produces the errors

ERROR:MapLib:30 - LOC constraint P126 on CLK is invalid: No such site on the
   device. To bypass this error set the environment variable 'XIL_MAP_LOCWARN'.
ERROR:MapLib:30 - LOC constraint P35 on SIGNAL is invalid: No such site on the
   device. To bypass this error set the environment variable 'XIL_MAP_LOCWARN'.
ERROR:MapLib:30 - LOC constraint P34 on x is invalid: No such site on the
   device. To bypass this error set the environment variable 'XIL_MAP_LOCWARN'.
ERROR:MapLib:30 - LOC constraint P33 on OUT.PAD is invalid: No such site on the
   device. To bypass this error set the environment variable 'XIL_MAP_LOCWARN'.

This is my first project in verilog, so I don't really know what's wrong. I'm trying to set up a simple testbunch like on page 8 of this for my code. The code with the UCF compiles just fine, so it must be something in the testbench. The testbench code is pretty similar to the code in the powerpoint, so I think it comes from my attempt to set local variables to certain values for the test and my not defining a different input. (I need to do this because to really test this it needs to have two inputs for SIGNAL, but I can't do this with the simple testbed described in the powerpoint. So I set the local variables to what they need to be and carry on.) However the errors seem to point to the UCF being the problem. So I don't really know what's going on.

Any help would be appreciated. I am using the Oracle VM Virtualbox ISE.

Code

module trapverilog(
    input CLK,
    input SIGNAL,
     input x,
     input SUM, // OUT is mapped to SUM on board
    output reg OUT
    );

reg[64:0] yregone;
reg[64:0] yregtwo;
reg[64:0] sum;

always @(posedge CLK)
begin
    yregtwo = yregone;
    yregone = SIGNAL;
    if (yregtwo != 0)
    begin
        sum = ((yregone + yregtwo)*x/2) + SUM; //treats x as plain h, change if treated as h/2
        OUT = sum;
    end
end

endmodule

User Config File

NET "CLK" LOC = P126;
NET "SIGNAL" LOC = P35 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST; 
NET "x" LOC = P34 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "OUT" LOC = P33 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST; 

Testbed

module testbed();
    reg CLK, SIGNAL, x, SUM;
    wire OUT;

// instantiate device under test
trapverilog dut(.CLK(CLK), .SIGNAL(SIGNAL), .x(x), .SUM(SUM), .OUT(OUT));

// apply inputs one at a time
initial begin
x = 1; CLK = 1; SUM = 0; trapverilog.yregone = 1; trapverilog.yregtwo = 2; #10; // apply input, wait
if (OUT !== 1.5) $display("failed."); // check
end
endmodule

endmodule

Selenium Webdriver-python, unable to find the dynamic element, tried all the possible ways

I am successfully able to navigate to the desired page after logging in. Static elements are located and printed, peacefully. The page makes JavaScript call and the contents are updated after about 4-5 seconds, I'm unable to locate the dynamic elements.

I'm attaching the image of Inspect element before and after loading of Javascript elements.

Please, have a look at the code below and suggest the possible solution. P.S. Out of 100 times this worked worked for about 2-3 times.

layer = "https://desired.website"
driver.get(layer)
driver.find_element_by_id("email").send_keys('my@email.com')
driver.find_element_by_id("password").send_keys('myPassword')
driver.find_element_by_class_name("css-173kae7").click()

#NOW I'M SUCCESSFULLY LOGGED IN
#Opening the Desired Page, This is a static element
wait = WebDriverWait(driver, 30)
element = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "css-1nga9gi")))
driver.execute_script('''window.open("desired.page","_blank");''')

#Successfully opened desired page and switched to newly opened tab
#Trying to access the element present in <tbody> tag, please refer "Inspect Element after JavaScript elements are loaded"- image.
wait = WebDriverWait(driver, 30)
element = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "css-167dqxg")))
check = driver.find_elements_by_class_name("ccss-13ozsj7")
for e in check:
    print(e.text)
print("ALL DATA SUCCESSFULLY PRINTED")

Nothing happens for 30 seconds and I get time-out error and "ALL DATA SUCCESSFULY PRINTED" is displayed.

ERROR CODE I GET IS:

element = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "css-167dqxg")))
File "C:\Python\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

Please have a look at the Inspect element.

Inspect Element at the beginning of Page Load

Inspect Element after JavaScript elements are loaded

Cypress Testing on Android Webview

I have been using Cypress Testing for automate navigation, and I would like to embed it in android to run it from a webview, maybe like:

getWebView(myWebView).evaluateJavascript(CypressJS, callback);

Any clue or advice is appreciated. Thanks.

Java Selenium cannot test Internet Explorer page error "org.openqa.selenium.os.OsProcess checkForError"

I am working with Selenium Driver in Eclipse (Java), I want to create a driver to test a Internet Explorer page and I keep getting this error message , my driver works fine with firefox and chrome but with explorer I cannot test anything

    System.setProperty("webdriver.ie.driver", "C:\\Users\\emorales\\Documents\\MicrosoftWebDriver.exe");
    //set webdriver to explorer  test
    WebDriver driver = new InternetExplorerDriver();

    //metodo para obtener url
    driver.get("http://google.com");

    System.out.println(driver.getTitle());

and this is my error message:

Jul 31, 2018 1:41:12 PM org.openqa.selenium.os.OsProcess checkForError SEVERE: org.apache.commons.exec.ExecuteException: Execution failed (Exit value: -559038737. Caused by java.io.IOException: Cannot run program "C:\Users\emorales\Documents\MicrosoftWebDriver.exe" (in directory "."): CreateProcess error=193, %1 is not a valid Win32 application) Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start. Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:32:14.902Z' System info: host: 'PCPSE0015', ip: '10.1.0.151', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '10.0.2' Driver info: driver.version: InternetExplorerDriver at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:193) at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:179) at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548) at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:212) at org.openqa.selenium.ie.InternetExplorerDriver.run(InternetExplorerDriver.java:221) at org.openqa.selenium.ie.InternetExplorerDriver.(InternetExplorerDriver.java:213) at org.openqa.selenium.ie.InternetExplorerDriver.(InternetExplorerDriver.java:150) at TEST3.main(TEST3.java:10) Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:13816/status] to be available after 20002 ms at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100) at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:188) ... 8 more Caused by: java.util.concurrent.TimeoutException at java.base/java.util.concurrent.FutureTask.get(Unknown Source) at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156) at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75) ... 9 more

Testing Express Middleware next('This is my Error Message')

Trying to test a middleware in Express that under some conditions calls next('my error message') and triggers an error. How it is possible to test this middleware in isolation? I'm seeing some good libraries for stubbing res and req but nothing for next. The behavior of triggering an error when passing a string to next needs to be available for this test to work

Method threw 'org.mockito.exceptions.misusing.InvalidUseOfMatchersException' exception.

I'm trying to test this method, however I am getting the following error:

Method threw 'org.mockito.exceptions.misusing.InvalidUseOfMatchersException' exception. 

On this line of Code:

    when(tester.method(
            any(String.class), any(LocalDate.class), any(boolean.class),any(boolean.class), any(String.class))).thenReturn(item);

API for Android Emulator

I have a task for the future - to create some online-based solution with Apps on Android Emulators and make smtg with App online using REST API. For instance, I have VM with Android SDK and WhatsAPP on them. I need click button on site to

1) login in WhatsAPP 2) send message 3) logout App in Android Emulator

I know how to install and make interesting scripts if I have Android Studio on my PC and only one App. But how to do "remote managing" App inside Emulator ? May be you could advise some solutions I could use with REST API to manage emulator with app inside?

Thanks!

Zuul not throwing expected exception

I am throwing a ZuulRuntimeException and written a test case to validate it but it is throwing a different one.

Code:

public String extractCdsid(String accessToken) {

        ObjectMapper objectMapper = new ObjectMapper();
        String cdsid = "";

        try {

            String payload = JwtHelper.decode(accessToken).getClaims();
            cdsid = objectMapper.readTree(payload).get("upn").textValue();

        } catch (NullPointerException e) {      
            ZuulException ex = new ZuulException(
                    "Token does not contain upn. Please send a valid that contains upn(cdsid)", 401, "");

            throw new ZuulRuntimeException(ex);     

        } }

Testcase:

@Test(expected = ZuulRuntimeException.class)
    public void getPrincipalHeader_withAuthorizationHeaderNotContainUpn_returnsException(){

        // mock
        MockHttpServletRequest req = new MockHttpServletRequest();
        req.addHeader("Authorization", "sendingtokenthatdoesnotcontainupn");

        // run
        tokenParser.getPrincipalHeader(req);        

    }

I am getting

java.lang.Exception: Unexpected exception, expected<com.netflix.zuul.exception.ZuulException> but was<java.lang.IllegalStateException>
    at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.IllegalStateException: CounterFactory not initialized
    at com.netflix.zuul.monitoring.CounterFactory.instance(CounterFactory.java:42)
    at com.netflix.zuul.exception.ZuulException.incrementCounter(ZuulException.java:73)
    at com.netflix.zuul.exception.ZuulException.<init>(ZuulException.java:54)
    at com.ford.cv.vadr.vadrgateway.util.TokenParser.extractCdsid(TokenParser.java:51)
    at com.ford.cv.vadr.vadrgateway.util.TokenParser.getPrincipalHeader(TokenParser.java:32)
    at com.ford.cv.vadr.vadrgateway.util.TokenParserTest.getPrincipalHeader_withAuthorizationHeaderNotContainUpn_returnsException(TokenParserTest.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
    ... 16 more

I see the correct exception being thrown with message when I hit the service throw postman

Using Jest property managers on arrays of objects

I am attempting to use Jest's new Property Matcher feature (since Jest 23.0.0) to match on an an array of objects that contain a generated field. I have tried putting both a plain object and a matcher definition using expect.arrayContaining and expect.objectContaining like I might when matching manually. Is there any way to do this currently?

const sportsBallPeople = [
  {
    createdAt: new Date(),
    name: 'That one famous guy from Cleveland'
  },
  {
    createdAt: new Date(),
    name: 'That tall guy'
  }
];
expect(sportsBallPeople).toMatchSnapshot(<something goes here>);

How to read a server based file with React

I am able to read a config.json file (using fetch) wich I included in my public directory with the "build" system, however when I test my system (yarn start ->localhost:3000) I get a 404, localhost:3000/config.json directly in my browser serves me this file. Any idea what to do?

Jest & Enzyme "TypeError: symbol is not a function"

I'm getting this error while trying to mount the Create Component:

TypeError: symbol is not a function

  50 |
  51 |     it('should render the dumb Create Component', ()=>{
> 52 |         wrapper = mount(
     |                   ^
  53 |             <Provider store={store}>
  54 |                 <Router>
  55 |                     <Create/>

It also tells me this: "The above error occurred in the component:"

that comes from this part of the code:

loadingIconDiv = () => {
    return(
        <div className="loadingIcon">
            <img width='100px' src={loadingIcon} alt='Loading...'/>
        </div>
    );
}

Here is my test:

it('should render the Create Component', ()=>{
    wrapper = mount(
        <Provider store={store}>
            <Router>
                <Create/>
            </Router>
        </Provider>
    );
    expect(wrapper).toHaveLength(1);
});

I've searched everywhere but haven't found anything related to this issue. Can someone help me out?

How to wait and go to a new URL with Nightwatch JS

So the scenario is that I am clicking on a button, and a loading pop up is displayed. What I am trying to achieve is that I want to wait for 5 seconds when the waiting pop-up is displayed and then navigate to a different URL.

So, I used browser.pause(5000) after the click but I am getting an error as:

TypeError: Cannot read property 'indexOf' of null

I can't use the web element of the loading pop-up because if I do it manually the pop up never stays on screen for more than a second.

Mutation testing for other tests than unit tests?

I have been reading up on Mutation Testing: the idea of a set of code, changing values in your code and re-running tests to see if you have code mutations on your hand.

Now, I am responsible for a large number of Functional Automation Tests; Regression and End-to-end. The more I read up on mutation testing, the more I see that it's mainly used for Unit Tests and not really anything else.

Is it also possible to apply Mutation testing to functional regression and end-to-end tests? Or perhaps even to Gherkin scripts?

Instance of found component equals to null using enzyme full mount

I have wizard component which i would like to test.

WizardComponent

class WizardComponent extends React.Component {
  render(){
    return (
      <div>
        {this.props.steps.map(({Component, ...props}) => <Component {...props} />)
      </div>
    )
  }
}

Test

it('Provides props to the component', () => {
 const FakeComponent = props => <div>1</div>

    const fakeProps = {
        test:1,
        prop4:'test'
    }

    const wrapper = mount(<WizardComponent currentStepName="fakeComponent" steps={[
        {Component:FakeComponent, name:'fakeComponent'},
    ]}/>)

    console.log(wrapper.contains(<FakeComponent />)) // logs true
    console.log(component) // logs ReactWrapper { length: 1 }
    console.log(component.instance()) // logs null

    expect(component.instance().props).objectContaining(fakeProps)

})

Why i can not access the component instance ?I would like to test its children components props.Can someone help?

VSTest task does not execute test dll(s) built for Platform x64

I am using Visual Studio Test task version 2 in my build definition in TFS 2017.Once my build is successful and it generates test dll(s),VSTest task is not able to run the test dll(s) that are built on platform x64.I am getting the following message:

Test run will use DLL(s) built for framework Framework45 and platform x86.Following DLL(s) will not be part of run: 'TestDllName.dll' is built for Framework FrameworkCore10 and Platform x64.

Has anyone faced this problem before??Please provide me suggestions to fix this.

Spring overrided AbstractXlsView.createWorkbook method is not called as supposed

I have two tests: for controller and view with overrided method createWorkbook.

Specifically I am testing download of xls document in controller while the document is created as view based on AbstractXlsView. It works fine with view set as autowired - corresponding ModelAndView is created and my overrided createWorkbook method is called.

However after I have tried to test the view directly the above method is not called and hence the test cannot be performed correctly (there is probably called default createWorkbook, but not my overrided method).

Where can be the root problem?

Create test suite with online version of visualstudio

I'm using the online version of the visual studio team server (myname.visualstudio.com)

I am able to create testcases, but I cannot seem to create a test-suite or a testplan.

Does anyone know how to do that?

What are the differences between MockBackend and HttpTestController?

When testing Angular services, when might I use HttpTestingController.expectOne(...).flush(...) or similar, and when would it be better to use MockBackend.connections.subscribe(...). Are these just a matter of preference or are there clear use cases that lend themselves to one approach over the other?

Issue with testing my function time converter

I'm trying to test my function but for me tests act unexpected way

def time_converter(time_zone=None, date_time=None):
    if not time_zone and not date_time:
        return None
    else:
        from_dt = datetime.strptime(date_time, '%Y-%m-%dT%H:%M:%S.%f')
        time_zone = pytz.timezone(time_zone)
        from_dt = from_dt.astimezone(time_zone)
        from_dt = from_dt.strftime('%Y-%m-%dT%H:%M:%S.%f%z')
        date_time = from_dt[:23]
        time_zone = from_dt[-5:]
        return date_time + time_zone

Here is my tests

class TestTimeConverter(unittest.TestCase):

    def test_none_datetime_timezone_converter(self):
        result = time_converter()
        self.assertIsNone(result)

    def test_ok_datetime_timezone_converter(self):
        time_zone = 'Asia/Bishkek'
        test = '2018-07-26T06:00:00.001+0600'
        input = '2018-07-26T06:00:00.001'
        result = time_converter(time_zone, input)
        self.assertEqual(result, test)

if i run tests on my local machine everthing is ok but when i push my code on the gitlab thiss issue apeare

def test_ok_datetime_timezone_converter(self):
    time_zone = 'Asia/Bishkek'
    test = '2018-07-26T06:00:00.001+0600'
    input = '2018-07-26T06:00:00.001'
    result = time_converter(time_zone, input)

  self.assertEqual(result, test)

E AssertionError: '2018-07-26T12:00:00.001+0600' != '2018-07-26T06:00:00.001+0600' E - 2018-07-26T12:00:00.001+0600 E ? ^^ E + 2018-07-26T06:00:00.001+0600 E ? ^^

 tests/test_time_converter.py:16: AssertionError
 ====================== 1 failed, 1 passed in 0.07 seconds ======================
 ERROR: Job failed: exit code 1

I tried to mock this class to return needed value but E TypeError: can't set attributes of built-in/extension type 'datetime.datetime'

lundi 30 juillet 2018

Samsung remote lab not showing device on android studio

I am using samsung test lab and i successfully run it on my ubuntu but when i try to run , it is not showing remote devices

enter image description here

enter image description here

Best way to test a web app on a specific phone without that phone

I need to test a web app on the S7 edge, however I don't have one. The web app works with other phones but for the S7 edge, the conversion rate is actually 0. What is the best way to test the way the phone is interacting with the web app, without owning the actual hardware.

I have android studio and was going to try using webview, but I think you need the device for that. I was thinking about using appium but I'm not sure if it would give me a diagnostics of what scripts were/weren't running.

Any suggestions?

How to stub file size on Active Storage test? (Test::Unit)

I'm using Active Storage in a personal project. I want to check if the max size of files is being validated. I don't wanna use a real file, but I don't know how to stub an object.

Here's the test code:

test "should not upload file bigger than max size allowed" do
  refute @page.file.attached?

  patch "/#{@page.url}", params: {
    page: {
      url: "/#{@page.url}",
      file: my_stub_file_with_big_size
    }
  }
  assert_response :not_acceptable
  @page.reload

  refute  @page.file.attached?
end

Here's the validation on model:

def file_size
  if file.attached? && file.byte_size > MAX_FILE_SIZE
    file.purge
    errors.add(:file, "File is too big. Max size is 20mb.")
  end
end

Drag and Assert Location Test

http://demoqa.com/draggable/

In the web page there are options for draggable testing, click on any option.

Code is able to drag the element but unable to assert its location properly

public void DraggableTest()
        {
            _dragPage.GoToUrl();
            _dragPage.CursorStyle.Click();

            Thread.Sleep(2000);

            _dragPage.Drag();

            Thread.Sleep(3000); 

            //_dragPage.DragSortObject.Location.Should().Be("{ X = 619,Y = 441}");

Any ideas ?

Custom testInstrumentationRunner only for specific tests

I have custom testInstrumentationRunner and I set it inside gradle this way:

`testInstrumentationRunner` `com.dom.androidtest.TestRunner`

But I want to run only specific tests with this testInstrumentationRunner. Is there a way to set my TestRunner for specific class, like @RunWith(AndroidJUnit4.class) for JUnitRunner?

Python hypothesis: Ensure that input lists have same length

I'm using hypothesis to test a function that takes two lists of equal length as input.

import hypothesis.strategies as st
from hypothesis import assume, given


@given(st.lists(ints, min_size=1),
       st.lists(ints, min_size=1),
       )
def test_my_func(x, y):
    assume(len(x) == len(y))

    # Assertions

This gives me the error message:

FailedHealthCheck: It looks like your strategy is filtering out a lot of data. Health check found 50 filtered examples but only 4 good ones.

The assumption that len(x) == len(y) is filtering out too many inputs. So I would like to generate a random positive number and use that as the length of both x and y. Is there a way this can be done?

Unable to run Meteor Test despite setting TEST_BROWSER_DRIVER in environment variables

I have not been able to test my meteor app at all, previously at v1.4, I managed to launch the tests, after upgrading to 1.6, I have not been able to run the tests despite my efforts. I hope anyone can help.

Operating System: Windows 10.

Current Meteor Version: 1.6

In my environment variables, I have set path to point to my chromedriver, but still no success at all.

 C:\Users\Username\Documents\Dev\Proj\infilerp>TEST_BROWSER_DRIVER=chrome meteor test --once --driver-package meteortesting:mocha
'TEST_BROWSER_DRIVER' is not recognized as an internal or external command,
operable program or batch file.  



C:\Users\Username\Documents\Dev\Proj\infilerp>meteor test --full-app --

driver-package meteortesting:mocha --port 8080
[[[[[ Tests ]]]]]

=> Started proxy.
=> A patch (Meteor 1.6.1.3) for your current release is available!
   Update this project now with 'meteor update --patch'.
=> Started MongoDB.
I20180730-17:58:52.807(8)? superadmin created
I20180730-17:58:53.166(8)?
I20180730-17:58:53.167(8)? --------------------------------
I20180730-17:58:53.167(8)? --- RUNNING APP SERVER TESTS ---
I20180730-17:58:53.168(8)? --------------------------------
I20180730-17:58:53.168(8)?
I20180730-17:58:53.168(8)?
I20180730-17:58:53.169(8)?
I20180730-17:58:53.169(8)?   0 passing (1ms)
I20180730-17:58:53.170(8)?
I20180730-17:58:53.171(8)?
I20180730-17:58:53.171(8)? --------------------------------
I20180730-17:58:53.172(8)? --- RUNNING APP CLIENT TESTS ---
I20180730-17:58:53.172(8)? --------------------------------
W20180730-17:58:53.281(8)? (STDERR) C:\Users\Username\AppData\Local\.meteor\packages\meteor-tool\1.6.1\mt-os.windows.x86_64\dev_bundle\server-lib\node_modules\fibers\future.js:280
W20180730-17:58:53.282(8)? (STDERR)                                             throw(ex);
W20180730-17:58:53.283(8)? (STDERR)                                             ^
W20180730-17:58:53.283(8)? (STDERR)
W20180730-17:58:53.283(8)? (STDERR) Error: Unknown driver "C:\Users\Username\Documents\Dev\Proj\infilerp\node_modules\chromedriver\lib\chromedriver\chromedriver.exe". browser-tests package requires that you set the TEST_BROWSER_DRIVER environment variable to one of the following: chrome, nightmare, phantomjs, puppeteer
W20180730-17:58:53.284(8)? (STDERR)     at startBrowser (packages/meteortesting:browser-tests/server.js:39:13)
W20180730-17:58:53.284(8)? (STDERR)     at clientTests (packages/meteortesting:mocha/server.js:138:3)
W20180730-17:58:53.284(8)? (STDERR)     at serverTests (packages/meteortesting:mocha/server.js:168:7)
W20180730-17:58:53.285(8)? (STDERR)     at mochaInstance.run.failureCount (packages/meteortesting:mocha/server.js:118:13)
W20180730-17:58:53.285(8)? (STDERR)     at done 

...    
=> Exited with code: 1

Unable to launch Cucumber tests with Idea

Unable to launch cucumber tests with Idea. Please, help.

My environment:

Idea 2018.2 with all latest update; Gradle 3.5; JDK 1.8.0_172; Latest cucumber plugin;

Dependencies

    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'io.appium', name: 'java-client', version: '5.0.2'
    compile group: 'io.qameta.allure', name: 'allure-junit4', version: '2.6.0'
    compile group: 'org.assertj', name: 'assertj-core', version: '3.9.1'

    testCompile group: 'io.cucumber', name: 'cucumber-junit', version: '3.0.2'
    testCompile group: 'io.cucumber', name: 'cucumber-java', version: '3.0.2'

Structure:

main -> baseclass -> BaseClass (core of my Appium/Selenium project)
test -> cucumbersteps: 
          - MyStepDefs
          - RunnerTest
test -> resources -> cucumbersteps -> open_day.feature

When i launching RunnerTest with command:

gradlew clean test --tests ru.cucumbersteps.RunnerTest

my tests is passing but when i trying to run tests with Idea configuration my tests failing with:

java.lang.NullPointerException


Failed scenarios:
1 Scenarios (1 failed)
6 Steps (1 failed, 3 skipped, 2 passed)
0m1,001s

I'm creating run configuration with Idea:

Main class: cucumber.api.cli.Main
Glue: ru.cucumbersteps
Feature: C:/git/JunitPOM/src/test/resources/cucumbersteps/01.open_day.feature
Arguments: --name "^Open day$"
Classpath: JunitPOM_test

Selenium Webdriver Function Continuity

So i have the following java code with a selenium webdrive code. The code works as intended untill the AddItems function. It does not work, I can't make it continue the work from the Login function. I've tried calling both function in the main, i've tried calling one AddItems into Login. I don't understand how i should link the two process so one continuies the other. I've tried what i've seen here: https://www.youtube.com/watch?v=ph3NJm4Z7m4&t=4472s , at 1:02:44 ish .

Please help me understand how can the function use the same "test" and continue the function.

package TestEmagShoppingCart;

import java.util.concurrent.TimeUnit;

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

public class ShoppingCart {

    WebDriver test;

    public void Login() throws InterruptedException

    {
        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
        WebDriver test = new ChromeDriver();
        test.get("http://www.emag.ro");
        test.manage().window().maximize();
        //test.manage().deleteAllCookies();
        //test.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        //test.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);

        String title = test.getTitle();
        System.out.println("Titlul paginii este: "+ title);

        test.findElement(By.xpath("/html/body/div[3]/nav[1]/div/div/div[3]/div/div[2]/a/span")).click();
        test.findElement(By.id("email")).sendKeys("anghelalex1994@gmail.com");
        Thread.sleep(1000);
        test.findElement(By.xpath("/html/body/form/div[4]/div/button")).click();
        Thread.sleep(1000);
        test.findElement(By.id("password")).sendKeys("alex21");
        test.findElement(By.xpath("/html/body/form/div[4]/div/button")).click();
        //test.findElement(By.xpath("/html[1]/body[1]/div[3]/div[1]/div[1]/div[1]/ul[1]/li[5]/a[1]")).click();
        //AddItems();
    }

    public void AddItems()
    {

        test.findElement(By.xpath("/html[1]/body[1]/div[3]/div[1]/div[1]/div[1]/ul[1]/li[5]/a[1]")).click();
    }

    public static void main(String[] args) throws InterruptedException {

        ShoppingCart cart = new ShoppingCart();
        cart.Login();
        cart.AddItems();

    }

}

State true or false: In JUnit, assertions are used to check for failure of tests

State true or false: In JUnit, assertions are used to check for failure of tests.State true or false: In JUnit, assertions are used to check for failure of tests.State true or false: In JUnit, assertions are used to check for failure of tests.State true or false: In JUnit, assertions are used to check for failure of tests.State true or false: In JUnit, assertions are used to check for failure of tests.State true or false: In JUnit, assertions are used to check for failure of tests.State true or false: In JUnit, assertions are used to check for failure of tests.State true or false: In JUnit, assertions are used to check for failure of tests.

PyTest: Auto delete temporary directory created with tmpdir_factory

I'm trying to create a temporary directory with a specific name (eg, "data") for all tests within a module using PyTest's tmpdir_factory similar to the tutorial:

@pytest.fixture(scope='module')
def project_file(self, tmpdir_factory):
    return tmpdir_factory.mktemp("data")

I'm using the temporary directory in some tests within the module successfully. However, the directory still exists after running the tests and when I run them again, I get a failure because I cannot create a new temporary directory with name "data".

How can I automatically delete the temporary directory "data" after the pytest tests finish? The tmpdir argument creates temporary directory that is removed but it doesn't have a name and it only has function scope.

javascript forEach manage exceptions

I have a forEach loop that check if there are conditions before pushing data in the array:

allow(id, perm, arr) {
  const data = { "userId": id, "permissionId": perm };

  arr.forEach(key => {
    if (id !== key.userId) {
      throw new Error('id does not exists');
    } else {
      if (perm === key.permissionId) {
        throw new Error('perm exists in this id');
      } else {
        arr.push(data);
      }
    }
  });
}

The original array arr is like this:

[{"userId": 1,"permissionId": 1},
 {"userId": 2,"permissionId": 1},
 {"userId": 3,"permissionId": 0},
 {"userId": 4,"permissionId": 0}]

if I use console.log() all works, but when I throw an error the execution stops, but how can I manage the exceptions without stop looping?

Selenium DragWithCursor Test

I want to build a test case where the mouse cursor moves with the element and then assert that the position of the mouse is relative to the element ?

Any ideas ?

https://pastebin.com/cnzSCzb9

public IWebElement CursorStyle => this.Driver.FindElement(By.Id("ui-id-3"));

public IWebElement DragObjectCursor => this.Driver.FindElement(By.Id("drag"));

public void DragWithCursor()
        {

            Actions action = new Actions(this.Driver);
            action.MoveToElement(this.DragObjectCursor)
                .ClickAndHold()
                .MoveByOffset(50, 50)
                .Perform();
        }

public void GoToUrl()
        {
            this.Driver.Url = "http://demoqa.com/draggable/";
        }

[Test]

public void DragElementCursorStyle()
        {
            _dragPage.GoToUrl();
            _dragPage.CursorStyle.Click();

            Thread.Sleep(2000);

            _dragPage.DragWithCursor();

            Thread.Sleep(3000);
        }

http://demoqa.com/draggable/

How to stub a method that is indirectly called inside another method

I've a node / express REST API. To test my UsersController.login method, that will indirectly call dbConnector.readDoc() function, I need to stub it. But I've not been succeeded. The stub is never called.

My Code:

//test.spec.js

  const db = require('../../../api/api.dbConnectors/couchdb.connector');

  it('STUB should return 404 Error response if NON EXISTING username on DB (passw irrelevant)', function () {
      var req = httpMocks.createRequest({
          body: {
              username: "undefUsername",
              password: 'irrelevant'
          }
      });
      var res = httpMocks.createResponse({
        locals: {
          statusCode: 404,
          message: 'Request failed with status code 404',
        }
      });

  const stubedReadUser = sinon.stub(db, 'readDoc');
  // override behavior
  stubedReadUser.rejects();
  // const p = stubedReadUser.rejects(res);
  UsersController.userLogin(req, res);
  expect(stubedReadUser).to.have.been.calledOnce;

  stubedReadUser.restore();
});

// api route

// FullPATH: /api/v1/users/...
// req.body = {username + password}
router.post('/login', UsersController.userLogin);

// UsersController.js

const db = require('../api.dbConnectors/api.db.connector');

function userLogin(req, res) {
  let user;
  let token;

  if (!ctrlHelpers.requestHasCredentials(req.body)) {
    return res.status(400).json({
      status: 400,
      message: 'Login failed: Bad request!',
    });
  }

  const userID = CONFIG.APP.USERS_NAMESPACE + req.body.username;
  db.readDoc('users', userID)
    .then((resp) => {
      // on success do something ...
    })
    .catch((err) => {
      return res.status(err.response.status).json({
        status: err.response.status,
        message: err.message,
      });
    });
}

// api.db.connector.js

// in the future will serve to select from MongoDB or CouchDB

const driver = require('./couchdb.connector');

module.exports = {
  createDoc: driver.createDoc,
  readDoc: driver.readDoc,
  updateDoc: driver.updateDoc,
  deleteDoc: driver.deleteDoc,
};

// couchdb.connector.js

module.exports = {
  readDoc,
  updateDoc,        
  (…)
};

async function readDoc(collection, docID) {
  const queryOptions = '?include_docs=true';
  const query = `${collection}${docID}${queryOptions}`;

  return axios.get(query);
}

Hope, someone could help me?

Vue is not rendered in Capybara test

I'm trying to test Vue.js from Rspec with Capybara. My problem is: the body is empty.

I was looking info for a few days and all the solutions is to change the driver of Capybara. I tried all but the bug persists.

My rails_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
require 'capybara/poltergeist'
require 'factory_girl_rails'
require 'capybara/rspec'

options = {js_errors: false}

Capybara.server = :puma
require 'rack_session_access/capybara'
require 'capybara/poltergeist'

RSpec.configure do |conf|
  conf.include FactoryGirl::Syntax::Methods
end

Capybara.register_driver :poltergeist do |app|
    Capybara::Poltergeist::Driver.new(app, options)
end
Capybara.javascript_driver = :poltergeist
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

RSpec.configure do |config|
  # RSpec Rails can automatically mix in different behaviours to your tests
  # based on their file location, for example enabling you to call `get` and
  # `post` in specs under `spec/controllers`.
  #
  # You can disable this behaviour by removing the line below, and instead
  # explicitly tag your specs with their type, e.g.:
  #
  #     RSpec.describe UsersController, :type => :controller do
  #       # ...
  #     end
  #
  # The different available types are documented in the features, such as in
  # https://relishapp.com/rspec/rspec-rails/docs
  config.infer_spec_type_from_file_location!

  # Filter lines from Rails gems in backtraces.
  config.filter_rails_from_backtrace!
  # arbitrary gems may also be filtered via:
  # config.filter_gems_from_backtrace("gem name")

  config.include FactoryGirl::Syntax::Methods # this allows to use factory girl gem's methods
  # this is to test javascript with capybara  
end

Then I have a feature test in spec/features/

require 'rails_helper'
require 'support/login_helper'

RSpec.feature "login", type: :feature, js: true do
  include LoginHelper

  before do
    login!
  end

  scenario 'a' do
    expect(true).to eq(true)
  end
end

And finally, my login helper when I have the error.

require 'rails_helper'

module LoginHelper
    def login!
        visit root_path
        print page.html
        fill_in "username", with: "aaa"
        click_button "Entrar"
    end
end

In the helper I try to visit the root_path, get the input and then fill with some mock data.

In the console, the test provides me the following error:

Failure/error: fill_in "username", with: "aaa"

Capybara::ElementNotFound:
   Unable to find visible field "username" that is not disabled

I print the page.html before the fill_in and I have

In the vue.app I'm using

How to run Laravel package tests?

I am creating a package and I want to write tests. There is a great library called Orchestral/Testbench created especially for package testing. But here is a problem: I do not know how to run tests properly.

I want to include some files so it would be easier to solve this problem (Gist link): https://gist.github.com/BobieBobie/43757036bc18fdea264f1f189368a17b

And here is my directory structure (screenshot): http://prntscr.com/kcnufs

When I am running the test from IDE (PHPStorm), it tells me, that it cannot find vendor/autoload within packages folder (it is obvious). But when I change the bootstrap path (in phpunit.xml) with "../../../vendor/autoload.php", it says:

Fatal error: Class 'Nod\Parser\Tests\IntegrationTest' not found As you could see my namesp

Help me, please. Ty in advance!

Use relative path in init function cannot be found in test

I'm running into an annoying problem when using relative path in the init function which cannot be found by the unit test.

Say I have a project structured like:

.
├── conf
│   └── blacklist
├── filter
│   ├── filter.go
│   └── filter_test.go

And in the init function of filter.go, I try to load the blacklist by using relative path conf/blacklist to avoid loading it multiple times. Since the default working directory is exactly the project root directory, it works well with compiled binary. However filter_test.go will panic by panic: open conf/blacklist: no such file or directory, becasue go test always uses the package directory as the working directory.

I also referred this solution, which could dynamically build the relative path to find the config file. It did work well until I add the covermode=set flag and try to do some coverage testing. It seems that the covermode would rewrite and generate some middle packages like _obj, which makes the dynamical relative path not working any more.

Has anyone run into the same problem before? I'm still new to golang for a couple of months. Any suggestions will be appreciated.

software testing flow charts and flow graph PDL

I'm studying Software Testing at my university and in the book I found this example page 490 7th edition software enginnering by roger s.pressman: it's a pseudocode that i want to convert in flow chart and flow graph. the book does'nt show the whole steps of flow graph i've tryed my best to learn it check different books websites and watched different videos but didn't get steps of converting code to flow graph. i've made this flow chart and need suggustion where i'm wrong because it is totally change from flow graph of book.enter image description here

Difference between format and value

Can we clearly make the difference between data format and data value in any kind of language (in a theoretic point of view?) or is the value of a data a sub-set of its format?

My objective here is to identify if an incoming data for a given function is correct. An instinctive way to do this is just to check the value you expect. But if the data is a structure (or a complex object), you will also check (in the way you want) if the structure or object received is the one you expect (with the correct format and the correct values).

An other good example is those of a signal where the shape (format) is different, but the values are in the same boundaries.

So do you guys think that these separation between data format and data value is something that make sense in a verification (for a critical system for example) point of view? Can we always make this separation or is it sometimes self included?

signal example

dimanche 29 juillet 2018

TFS Test Chart - How to assign the test result chart to be displayed in dashboard till the sprint end date?

I want the test result chart should be displayed in dashboard till the sprint end date after that it should be removed automatically and the new sprint test chart should be displayed. The problem i am getting is, i have started the new sprint but the old sprint test chart is still displaying in the dashboard.

TypeError: fn.call is not a function

So I'm using Appium with WebdriverIO to run tests and right now I'm trying to call/reference functions from a dictionary file. But I keep getting "TypeError: fn.call is not a function" everytime I try to call the function from another file instead of copy pasting the function.

Here's a snippet of the relevant codes:

//File I'm trying to reference
exports.toLoginPassword=function() {
      return client
        .waitForExist('android=new UiSelector().resourceId("com.orgname.dcpApp:id/frmAppLanding")')
        .setValue('android=new UiSelector().resourceId("com.orgname.dcpApp:id/tbxEntry")', input.username)
        .click('android=new UiSelector().resourceId("com.orgname.dcpApp:id/flxLoginActions")')
        .waitForExist('android=new UiSelector().resourceId("com.orgname.dcpApp:id/frmLoginPassword")')        
        .then(function (result){
          assert.equal(result, true)
        })
      }
 describe('Log in', function() {
    it('should go to full login page', `${dictionary.toLoginPassword}`)

What is wrong with my unit testing?

I am new to unit testing.... can anyone help to correct my test, since my assertions are returning false and my test keeps failing, but I don't know if that is because I've written the test wrong or if the code being tested is wrong. Please help.

This is the code: public static String getTokenWithAppIdentity( String resource, String clientId, String clientSecret, String authority) throws IOException {

    String body = "resource=" + URLEncoder.encode(resource, java.nio.charset.StandardCharsets.UTF_8.toString())
            + "&client_id=" + URLEncoder.encode(clientId, java.nio.charset.StandardCharsets.UTF_8.toString())
            + "&client_secret=" + URLEncoder.encode(clientSecret, java.nio.charset.StandardCharsets.UTF_8.toString())
            + "&grant_type=client_credentials";

    return handleAuthRequest(body, authority);
}

and this is the test:

@Test
public void test_get_token_with_app_identity() throws IOException {

    PowerMockito.mockStatic(URLEncoder.class);
    Mockito.when(URLEncoder.encode(Mockito.anyString(), Mockito.anyString())).thenReturn("answer");

    PowerMockito.mockStatic(Authenticate.class);
    Mockito.when(Authenticate.handleAuthRequest(Mockito.anyString(), Mockito.anyString())).thenReturn("TOKEN");

    String result = Authenticate.getTokenWithAppIdentity("", "", "", "");

    Assert.assertNotNull(result);
    Assert.assertEquals("TOKEN", result);
}

How can I inject property source of a bean in test

I am writing unit tests for my services in Spring, Java. I mock all dependencies in a tested class and I instantiate the tested class in a constructor, to which I pass mocked classes. The problem is that the tested class injects properties from .properties file into fields that are inside it (let's say Strings).

I use the standard combination of @PropertySource on a class level and @Value on a field level inside my tested class.

As we know, properties injection fails when class is instantiated through constructor (not as a bean during the Spring Container initialization). How do you deal with such problem?

I've got one solution, though I think it is bad and unsatisfactory, that is: 1. to @Autowire the class under test normally, then replace all its dependencies by using a setter.

I also know about the @TestPropertySource annotation and if I understand correctly, it does not provide a solution and it is only a way to override already existent properties - which is not the case, as we cannot really use any properties.

Thanks for help in advance :)

How to use custom comparator / diff in PAssert of PCollection

I have a code similar to the one below transforming a PCollections of Protocol Buffer messages. Because some of them are pretty big I want to not only test it using for equality but also print where's the difference.

I want to use https://google.github.io/truth/fuzzy tests which offer to print a difference.

PCollection<PbMsg1> p1 = ...;
List<PbMsg1> p2 = loadFixture();

PAssert.that(p1).containsInAnyOrder(output.getUserReqList());

The question is either:

  1. How to use custom diff / compare function in PAssert?
  2. How to convert from a PCollection to List?

Test failed to run to completion. Reason: 'Instrumentation run failed due to 'java.lang.NullPointerException''. Check device logcat for details

Test failed to run to completion. Reason: 'Instrumentation run failed due to 'java.lang.NullPointerException''. Check device logcat for details

Is there a way to compile a solution from a unit test and fail the test if the compile fails?

I want to overwrite the Program.cs file in a solution I have created for a test, and then compile that solution - as a unit test.

With our library we have in the designer that comes with it a button titled Generate Code. When you click that button it pops up with the code for a sample Program.cs file that calls our library specifically written for the template created in the designer.

We want to have a unit test that verifies that the code we created compiles. We're not testing that it runs, just that it compiles. So the thought is we create a project, replace the Program.cs file in the project, and then compile the project. Successful compile, the test passes. Compile fails, the test fails.

What's driving this is we had a mistake in the code where it had "${name}.compile()" instead of $"{name}.compile()" - and that will easily be found with this.

So, can it be done?

How do I find and select a dropdown value with selenium using C# in visual studio 2017

I am trying to locate an element within a dropdown list with selenium. How can I do this. Attached are images which describes the situation. I want to do this using the IWebElement function.

Ive tried using the following-

IWebElement Depart = driver.FindElement(By.XPath("///input[@name='fromPort' and @value='Sydney']"));

but it does not work!! How can I select Sydney from the drop-down list?

enter image description here

samedi 28 juillet 2018

How to use a factory within a factory with Laravel?

I have a factory creating StreetAddresses and I want to use it in my factory that creates CreditCards.

GOOD: This behaves as expected, creating a CreditCard object with an stdClass for the street_address and the properties are all good.

<?php
use FuquIo\LaravelAccounting\Orm\CreditCard;
use FuquIo\LaravelCommonRelatables\Locatable\StreetAddress;
use FuquIo\LaravelUser\Access\User;

$factory->define(CreditCard::class, function (\Faker\Generator $faker){

$street_address = factory(StreetAddress::class)->make();

return [
    'customer_id'    => User::root()->getKey(),
    'cardholder'     => $faker->firstName . ' ' . $faker->lastName,
    'nick_name'      => $faker->company,
    // LOOK HERE: this works
    'street_address' => function () use ($street_address) { return (object) $street_address->toArray(); }
];

});

NOT so good: This returns null for the street_address.

<?php
use FuquIo\LaravelAccounting\Orm\CreditCard;
use FuquIo\LaravelCommonRelatables\Locatable\StreetAddress;
use FuquIo\LaravelUser\Access\User;

$factory->define(CreditCard::class, function (\Faker\Generator $faker){

$street_address = factory(StreetAddress::class)->make();

return [
    'customer_id'    => User::root()->getKey(),
    'cardholder'     => $faker->firstName . ' ' . $faker->lastName,
    'nick_name'      => $faker->company,
    // LOOK HERE AGAIN: this makes a null
    'street_address' => function () use ($street_address) { return $street_address; }
];

});

What I'd like, is to produce a CreditCard with a StreetAddress as a property.

What is the default test framework for ReactJS?

By using Create-React-App to scaffolding a new project, it will include default App.test.js with below content:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);

  //expect(div.innerHTML).toContain('Hi There!');

  ReactDOM.unmountComponentAtNode(div);
});

I've tried to run command yarn test, below is the response i got

Error: Cannot find module '/Users/isaaclem/Code/ReactJS/testing/node_modules/jest-cli'

And if I try npm run test instead, I'm hitting same error too, which saying couldnt find jest-cli. Is there any reason where C-R-A gives us a default test file but not including the necessary framework/module?

Below is the default package.json:

{
  "name": "testing",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-router-dom": "^4.3.1",
    "react-scripts": "1.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Calling a managed dll from Test Project

I have been facing a weird problem, where i write a code that wraps the calls to a dll of 3rd party system , the code itself is working correctly -it communicates with another SW , so it has to establish a connection within a configured time - when run from a console application.

When tried to run the same code from a Testing Project (a class library project that has nunit nuget pkg) it gives a different behavior(mainly time out after less time). i know that this is not a unit test for sure, but this is not the point , the main issue is a code that is run with a different behavior in the Testing Project i have tried Ms Test and Nunit.

based on this post(Is this DLL managed or unmanaged?) this dll is managed. I do not use any dll imports syntax neither in the source code nor in the testing code. Any suggestions are much appreciated.

Mock imports to test function logic

Lets say I have the following file.

This file imports promiseFunction from a library and I'd like to test the doSomething() function.

In particular, assert the states when the promise resolves or fails

// file: MyComponent.js

import promiseFunction from 'somewhere`;

class MyClass extends Component {

  doSomething = () => {

    promiseFunction()
      .then((data) => {

        this.setState({...this.statename: data.name});

      }.catch(() => {

        this.setState({...this.state, error: 'error'});

      });

  }
}

How do I mock the promiseFunction thats being imported. Or really just any function that's being imported.

Selenium not inputing strings based on name?

Im trying to create some tests in C# visual studio with selenium. When I run the test, google chrome navigates to the specified website, however no keys/strings are entered into the username and password fields...

Why is this? How do I fix this? How can I create a test which has the user enter the correct username and password queries and click on the submit form.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using NUnit.Framework;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;


namespace test
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            IWebDriver driver = new ChromeDriver("/Users/name/Desktop/test/");

            driver.Navigate().GoToUrl("http://newtours.demoaut.com/mercurywelcome.php");

            IWebElement username = driver.FindElement(By.Name("userName"));
            username.SendKeys("mercury");

            IWebElement password = driver.FindElement(By.Name("password"));
            password.SendKeys("mercury");

            var signIn = driver.FindElement(By.Name("login"));
            signIn.Submit();


        }
    }
}

Error CS0103: The name 'TimeSpan' does not exist in the current context (CS0103) (testingProgram)?

I am trying to create tests in C# with selenium driver in visual studio. I get the following error. Error CS0103: The name 'TimeSpan' does not exist in the current context (CS0103) (testingProgram) ?? I also have a second error displayed in the images provided. The code uses the PageObjectPattern >> https://www.automatetheplanet.com/page-object-pattern/

Btw I am using a mac.

How do I fix this? Can someone try and run the program to see if it is running on their end?? How do I get this program to run successfully?

enter image description here enter image description here

here is the following code-

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Support.UI;

[TestClass]
public class SearchEngineTests
{
    public IWebDriver Driver { get; set; }
    public WebDriverWait Wait { get; set; }

    [TestInitialize]
    public void SetupTest()
    {
        this.Driver = new FirefoxDriver();
        this.Wait = new WebDriverWait(this.Driver, TimeSpan.FromSeconds(30));
    }

    [TestCleanup]
    public void TeardownTest()
    {
        this.Driver.Quit();
    }

    [TestMethod]
    public void SearchTextInSearchEngine_First()
    {
        SearchEngineMainPage searchEngineMainPage = new SearchEngineMainPage(this.Driver);
        searchEngineMainPage.Navigate();
        searchEngineMainPage.Search("Automate The Planet");
        searchEngineMainPage.ValidateResultsCount("264,000 RESULTS");
    }
}

here is the second file-

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Support.UI;

[TestClass]
public class SearchEngineTests
{
    public IWebDriver Driver { get; set; }
    public WebDriverWait Wait { get; set; }

    [TestInitialize]
    public void SetupTest()
    {
        this.Driver = new FirefoxDriver();
        this.Wait = new WebDriverWait(this.Driver, TimeSpan.FromSeconds(30));
    }

    [TestCleanup]
    public void TeardownTest()
    {
        this.Driver.Quit();
    }

    [TestMethod]
    public void SearchTextInSearchEngine_First()
    {
        SearchEngineMainPage searchEngineMainPage = new SearchEngineMainPage(this.Driver);
        searchEngineMainPage.Navigate();
        searchEngineMainPage.Search("Automate The Planet");
        searchEngineMainPage.ValidateResultsCount("264,000 RESULTS");
    }
}

How to identify fields that were accessed or changed during a method execution without existing code modification

This is for testing purpose. I am trying to figure out during a method execution, how to identify fields that were accessed or modified. The fields can be public, private, from the object's superclass, parent class, outer class, etc.

For example, I have some code written by someone else, bottom line, I am not allowed to modify their code or at least the existing data structure of its classes. And they did not use setter and getter for most of the field changes. Adding a few lines of code at the beginning of a method and before the return is allowed for invoking my own implemented listener method.

public class MyClass {
    public String field1;
    public MyOtherClass field2;
    public String[] field3;

    public void method1(){
        field1 = "changed"; //field changed
        String st = field1; //field accessed
    }
}

Any recommendations?

test test test test test test test test test test test test

I tried calling ct:run_test/1 in a test case in the first module like this:

-module(ct_hook_SUITE).

my_test_case(_Config) -> Result = ct:run_test([{suite, [ct_hook_usage_SUITE]}, {ct_hooks, [hook]}, {logdir, "logs/example_test"}]), ct:pal("~w", [Result]), ok. But I got the following error:

common test {error,{error,interactive_mode}} I don't really understand this error and there aren't any options related to interactive mode for ct:run_test/1. Any suggestions?

Testing javascript code on asp.net mvc web app?

The app we are currently working on is a mix of server-side (asp.net mvc) and javascript code. Our front end developer is an experienced javascript developer but does not have any experience with visual studio and c#.

What would be a way for him to test the code he is working on without using visual studio? Is there actually a way to do so or the only alternative is for him to learn the basics of visual studio and c#?

Why Mocha.js can't find the module ?

I can't figure out why mocha.js can't find my path ! Here's the file structure that I included in my project for the node course

  ///////Root
  --package.json
  --node_modules/
  --playground
  --server
     -server.js
     -db
     -models
     -tests
           ---server.test.js

Every time I run "mocha server/**/*.test.js" I get this error from the command prompt after running the test command from the command prompt :

    > todo-api@1.0.0 test C:\Users\Omar Ali\Desktop\node-todo-api
> mocha server/**/*.test.js

module.js:549
    throw err;
    ^

Error: Cannot find module '../server/server'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\Users\Omar Ali\Desktop\node-todo-api\server\tests\
server.test.js:6:9)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at C:\Users\Omar Ali\Desktop\node-todo-api\node_modules\mocha\lib\mocha.js:2
50:27
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (C:\Users\Omar Ali\Desktop\node-todo-api\node_modules\moc
ha\lib\mocha.js:247:14)
    at Mocha.run (C:\Users\Omar Ali\Desktop\node-todo-api\node_modules\mocha\lib
\mocha.js:576:10)
    at Object.<anonymous> (C:\Users\Omar Ali\Desktop\node-todo-api\node_modules\
mocha\bin\_mocha:637:18)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! todo-api@1.0.0 test: `mocha server/**/*.test.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the todo-api@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Omar Ali\AppData\Roaming\npm-cache\_logs\2018-07-28T18_00_
44_790Z-debug.log

need a fake rest server which supports POST ,PUT methods which accepts headers and post/put body

I am testing an application which accepts http/https rest requests, for that I need few open source rest calls, where I can use POST, PUT calls which must use headers and POST/PUT body. Can anyone please share any link, where I can get such free apis to test. I found many such rest apis but those works irrespective of headers. Can anyone please share such api list which must need header and post body?

Thanks in Advance

java.lang.NoClassDefFoundError: org.mozilla.javascript.tools.debugger.treetable.JTreeTable

I encounter below exception when running android instrumentation test under all module. FYI, tested with both 'org.mozilla:rhino:1.7.7' & 'org.mozilla:rhino:1.7.9' latest version.Happens only when running instrumentation test. App running with no issue.

Logcat captured :

`07-27 23:39:22.208 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.assertj.core.internal.cglib.transform.AbstractProcessTask 07-27 23:39:22.209 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:22.210 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.assertj.core.internal.cglib.transform.AbstractTransformTask 07-27 23:39:24.035 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.036 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.036 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.ContextWindow 07-27 23:39:24.040 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.040 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.EvalTextArea 07-27 23:39:24.042 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.042 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.EvalWindow 07-27 23:39:24.043 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.044 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.Evaluator 07-27 23:39:24.045 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.046 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.046 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.FileHeader 07-27 23:39:24.047 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.047 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.FilePopupMenu 07-27 23:39:24.048 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.049 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.FileTextArea 07-27 23:39:24.050 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.055 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.056 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.FileWindow 07-27 23:39:24.057 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.057 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.FindFunction 07-27 23:39:24.058 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.058 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.JSInternalConsole 07-27 23:39:24.060 19504-19583/com.xxx.xxx.xxx.test W/AndroidJUnit4Builder: java.lang.NoClassDefFoundError: java.awt.Dimension in hasTestMethods for org.mozilla.javascript.tools.debugger.Main 07-27 23:39:24.070 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.071 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.071 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.Menubar 07-27 23:39:24.072 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.072 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.MoreWindows 07-27 23:39:24.073 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.073 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.MyTableModel 07-27 23:39:24.073 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.074 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.074 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.MyTreeTable 07-27 23:39:24.076 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.076 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.SwingGui 07-27 23:39:24.077 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.078 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.078 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.VariableModel 07-27 23:39:24.079 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class Rejecting re-init on previously-failed class java.lang.Class 07-27 23:39:24.079 19504-19583/com.xxx.xxx.xxx.test E/TestLoader: Could not find class: org.mozilla.javascript.tools.debugger.treetable.AbstractCellEditor 07-27 23:39:24.079 19504-19583/com.xxx.xxx.xxx.test I/art: Rejecting re-init on previously-failed class java.lang.Class

java.lang.NoClassDefFoundError: org.mozilla.javascript.tools.debugger.treetable.JTreeTable at java.lang.Class.classForName(Native Method) at java.lang.Class.forName(Class.java:309) at android.support.test.internal.runner.TestLoader.doCreateRunner(TestLoader.java:76) at android.support.test.internal.runner.TestLoader.getRunnersFor(TestLoader.java:110) at android.support.test.internal.runner.TestRequestBuilder.build(TestRequestBuilder.java:809) at android.support.test.runner.AndroidJUnitRunner.buildRequest(AndroidJUnitRunner.java:487) at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:373) at com.xxx.support.test.xxxTestRunner.onStart(xxxTestRunner.java:13) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1853) 07-27 21:47:04.930 1084-2189/system_process W/ActivityManager: Error in app com.xxx.xxx.xx.test running instrumentation ComponentInfo{com.xxx.xxx.xxx.test/com.xxx.xxx.xxx.xxxTestRunner}: java.lang.NoClassDefFoundError java.lang.NoClassDefFoundError: org.mozilla.javascript.tools.debugger.treetable.JTreeTable`

If remove implementation 'org.mozilla:rhino:1.7.7' in build grade and remove all javascript execution, the test is running with no issue. Tested with Android 6.0,5.1.1 devices.


test set up

After a lot of trying, fount out that when running test under "all in module" selection will throw above classNoFound issue; but when running with "all in package" selection and specific the package path, instrumentation test run with no issue.

meteortesting:mocha does not produce nice output

The recommended testing framework for Meteor 1.7 seems to be meteortesting:mocha.

With a default created app (meteor create my-app), which has the following tests

import assert from "assert";

describe("my-app", function () {
  it("package.json has correct name", async function () {
    const { name } = await import("../package.json");
    assert.strictEqual(name, "noteit");
  });

  if (Meteor.isClient) {
    it("client is not server", function () {
      assert.strictEqual(Meteor.isServer, false);
    });
  }

  if (Meteor.isServer) {
    it("server is not client", function () {
      assert.strictEqual(Meteor.isClient, false);
    });
  }
});

I ran

meteor add meteortesting:mocha
meteor test --driver-package meteortesting:mocha

and got this in the console:

I20180728-12:06:37.729(2)? --------------------------------
I20180728-12:06:37.729(2)? ----- RUNNING SERVER TESTS -----
I20180728-12:06:37.729(2)? --------------------------------
I20180728-12:06:37.729(2)? 
I20180728-12:06:37.730(2)? 
I20180728-12:06:37.731(2)? 
I20180728-12:06:37.737(2)?   the server
    ✓ fails a test.753(2)? 
I20180728-12:06:37.755(2)? 
I20180728-12:06:37.756(2)? 
I20180728-12:06:37.756(2)?   1 passing (26ms)
I20180728-12:06:37.756(2)? 
I20180728-12:06:37.757(2)? Load the app in a browser to run client tests, or set the TEST_BROWSER_DRIVER environment variable. See https://github.com/meteortesting/meteor-mocha/blob/master/README.md#run-app-tests
=> Exited with code: 0
=> Your application is crashing. Waiting for file change.

Actually, it was repeated three times. Not pretty. And I wasn't expecting a passing test to crash my app.

Also in the browser I got this

enter image description here

I was expecting something more like the nice output, as per the Meteor testing guide:

enter image description here

JSDom 11.12.0 - how to mock localStorage?

Since the latest release of JSDom, I'm not able to mock localStorage anymore.

I've tried the following methods:

  1. Object.defineProperty(window, 'localStorage', {value: LocalStorageMock})
  2. window.localStorage = LocalStorageMock;
  3. jest.spyOn(window.localStorage, 'setItem')

Any of those methods not worked for me, I've get all the time the original localStorage.

vendredi 27 juillet 2018

Jest unit test - global variable modified in a function which is being tested is undefined

I'm new to JEST and trying to write unit test cases for a tsx file. I'm trying to test a function which takes in an argument and sets the value of a global variable (x) equal to the argument passed. When I run the test, I get the value as undefined. Here is the code :

Function to be tested

  countrySelectedHandler (selectedCountry) {
    this.selectedCountry = selectedCountry.target.value;
    this.countrySelected.emit(selectedCountry.target.value);
  }

Unit Test

  it('should set the passed argument as selected country', () => {
    let country = { target : { value: '' } } ;
    country.target.value = 'India';
    obj.languageSelectedHandler(country);
    expect(obj.selectedLanguage).toEqual('India');
  });
});

How to put invalid id to get request?

I have issue with testing. I have to check that if user trying to get object which does not exist he must get 404 page.

Here is my route:

Route::get('/posts/{id}', 'PostController@index');

Here is my test:

public function testViewsA404PageWhenPostIsNotFound()
{
    $resp = $this->get('/posts/INVALID_ID');
    $resp->assertStatus(404);
    $resp->assertSee("The page a you looking for could not be found");
}

DB - PostgreSQL

But I get exception:

Illuminate\Database\QueryException: SQLSTATE[22P02]: Invalid text representation

invalid input syntax for integer: "INVALID_ID" (SQL: select * from "posts" where "posts "."id" = INVALID_ID limit 1)

I saw that in one lecture course but they used MySQL as database.

Can we pass conditional parameters to fixture functions in pytest?

I want to pass a list as a parameter to fixture based on a if condition. Is there a way to do this?

For example, please see the following code.

What I want to achieve is that if I pass odd as the num type in command line argument in pytest, the list passed as parameter to the fixture should be odd numbers and even numbers for argument even.

P.S I am using pytest-xdist to run this tests multiple times, hence I use sys.stderr to print output.

filename: conftest.py

def pytest_addoption(parser):
    parser.addoption('--type', action='store', help='Number of times to repeat each test')  

filename: test_file.py

import pytest, sys

lis = []

@pytest.fixture()
def nested_fixture(pytestconfig):
    global lis
    numtype = str(pytestconfig.getoption("type"))

    if numtype == "odd":
        lis.append(1)
        lis.append(3)

    if numtype == "even":
        lis.append(2)
        lis.append(4)

    return lis

@pytest.fixture(params = nested_fixture)
def fixture_function(request):
    return request.param


def test_function(fixture_function):
    print >> sys.stderr , fixture_function

I execute this using the following command in terminal

pytest -sv -n 2 --type odd

How do I mock a specific function from a module for a specific test

I have an api.js file that contains my api call. It looks like this:

// api.js

// reusable fetch call
export const makeFetch = async (url, options) => {
  try {
    const response = await fetch(url, options);

    if (!response.ok) {
      throw new Error(`${response.status}`);
    }

    return await response.json();
  } catch (error) {
    throw new Error(`Network request failed. (error: ${error.message})`);
  }
};

// actual fetch call
export const getCards = async () => {
  const url = 'http://localhost:3001/api/v1/cards';
  return await makeFetch(url);
};

Then I have an api.test.js file that looks like:

//api.test.js

import { makeFetch, getCards } from './api';

describe('makeFetch', () => {

  // three successful tests

});

// this is where I have issues

describe('getCards', () => {
  it('calls makeFetch', async () => {

    await getCards();

    expect(makeFetch).toHaveBeenCalledTimes(1);
  });
});

this is the error I get:

FAIL  src\api\api.test.js
  ● getCards › calls makeFetch

    ReferenceError: makeFetch is not defined

      at Object.it.only (src/api/api.test.js:51:15)
          at new Promise (<anonymous>)
      at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:182:7)

Does anyone know how to make this pass with making my previous tests fail? Thank you for your time.

How do I set up selenium based tests in C# in visual studio?

I am new to testing using selenium. I want to know how I can create a test in visual studio which tests if the user navigates to a webpage. What packages/dependencies do I need? what sort of project file do I need to open in visual studio i.e normal project in .NET or xUnit testing project etc. I am using a MAC.

below is something I tried to create but for some reason it did not work. Am I doing something wrong? I clicked on build and it said successful. Then I clicked on run but the test didnt do anything.

imageDescription

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;

using OpenQA.Selenium.Support.UI;

namespace test
{
    [TestFixture()]
    public class Test
    {



        [Test()]
        public void TestCase()
        {
            IWebDriver driver = new ChromeDriver("/Users/andrew/Desktop/test/chromedriver");

            //Navigate to google page
            driver.Navigate().GoToUrl("http:www.google.com");

        }
    }
}

How to set up unit tests for Backbone web application

I am working on a single-page web application built with Backbone.js, Marionette.js, jQuery, Handlebars and other front-end libraries. The application uses server APIs to interact with its back-end. I am interested in setting up and writing unit tests for the front-end logic that is growing in size and complexity.

What tools do people use in the industry to test the front-end of a web application? How difficult is it to set up and use? Is there a front-end testing framework that can be used with a Backbone.js application?

I know about mock servers and I don't want to test the front-end with those. I would like to test the JavaScript code (client logic) of a Backbone + Marionette app.

Thank you.

Protractor: Run tests using environment specific params from CLI

I am working on a protractor typescript testing framework and would like to run tests in different environments depending upon the env specific params that I send in CLI. For example: I want to run my test as "npm test SIT" or "npm test dit". The base url picks the url for SIT in case 1 and DIT in case2 to launch the application in different SIT and DIT environments.

I have made a file name Url.js(root/ data/ Url.js)

'use strict';
var env = browser.params.environment;

module.exports = {
  baseURL: function() {
    var baseUrl = '';
    if (env.toLowerCase().indexOf('sit') === -1) {
      baseUrl = 'https://'+env+'-site.com/app/home';
    } else if(env.toLowerCase().indexOf('dit') === -1){
      baseUrl = 'https://'+env+'-site.com/app/home';
    } else if(env.toLowerCase().indexOf('rit') === -1){
      baseUrl = 'https://'+env+'-site.com/app/home';
      }
    return baseUrl;
  }, 
  internalPage1: 'app/page/details/fff/ttt.html'  
};

Here is my config.ts

let path = require('path');
import { browser, Config } from "protractor";
import { Reporter } from "../support/reporter";
import * as oracledb from 'oracledb';
const jsonReports = process.cwd() + "/reports/json";


export const config: Config = {
    params:{
        environment: 'fdi', //dit or rit can be passed from cmd line        
    },

    seleniumAddress: "http://localhost:4444/wd/hub",

    SELENIUM_PROMISE_MANAGER: false,    

    capabilities: {

        browserName: 'chrome',
        maxInstances: 6

    },

    framework: "custom",
    frameworkPath: require.resolve("protractor-cucumber-framework"),

    specs: [
        "../../features/automation/regression/*.feature",
    ],

    onPrepare: () => {
        browser.ignoreSynchronization = true;
        browser.manage().timeouts().implicitlyWait(12000);
        browser.manage().window().maximize();
        Reporter.createDirectory(jsonReports);      

    },

    cucumberOpts: {
        compiler: "ts:ts-node/register",
        format: "json:./reports/json/cucumber_report.json",
        require: ["../../typeScript/stepdefinitions/*.js",
         "../../typeScript/support/*.js", 
         "../../dbUtils/index"],
        strict: true,
        tags: "@dataTable",        
        restartBrowserBetweenTests: true


    },

    onComplete: () => {
        Reporter.createHTMLReport();
    },
};

Cucumber hooks:

const { BeforeAll, After, AfterAll, Status, setDefaultTimeout, Before  } = require("cucumber");
import * as fs from "fs";
import { browser } from "protractor";
import { config } from "../config/config";
import { build$ } from "protractor/built/element";
var env = browser.params.environment;

//setDefaultTimeout(600 * 1000);

Before(async function ()  {
    await browser.get(env);
});

After(async function(scenario) {
    if (scenario.result.status === Status.FAILED) {
        // screenShot is a base-64 encoded PNG
         const screenShot = await browser.takeScreenshot();
         this.attach(screenShot, "image/png");
    }    
});

 AfterAll(async () => {
     await browser.quit();
 });

I dont know if I should call Url.js in my config.ts, I think I do but I am not sure how that could be done. Could someone give me some pointers as to who I can nail this down?

Django - runserver in "test-mode" with test databases

I'm trying to create tests for my Django application but I'm having some trouble creating a test database.

I'd like to keep the existing structure while entering new curated test-information, creating test users, uploading test content, etc. Which I can then populate a test database with so that I have curated data on which I can test edge-cases.

Creating a test database seems simple, just run python manage.py test --keepdb. Getting entries into it seems more difficult.

Is it possible to run django in "test mode" with the test database being used so that I can use the website UI to enter all the data, or is there some other better way to do it entirely?

How to mock e2e tests in angular 6

I'm trying mock the httpClient requests, but I don't know how to do this.

I was search for answers and I found this module: ng-apimock. Seems that is used to mock http requests when you make the e2e tests. If you have an example to show, please put the link here.

I read this README that explain how to implement this module in angular 2+ project, but it was not clear to me how to implement.

Can someone explain how mock my e2e tests in angular 6?

Embedded Jetty: How to set the JMX port in source code

We have system tests and when they start an Embedded Jetty boots via the setup. The Embedded Jetty includes a JMX server, too. Then we have tests which must connect to the JMX Server via:

JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:<JMX_PORT>/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);

The problem is we cannot connect from the tests to the JMX server when we do not know the JMX port up front. Has anybody a clue how to specify the JMX port up front when the Embedded Jetty is built within the source code? The system property stuff is of no help here.

Passing JSON file as source to JUnit test case

I have a dataset stored in a JSON file. Is there any way to pass that json to JUnit test case.

Taking @CSVFileSource as reference I am looking for something like this.

@ParameterizedTest
@CsvFileSource(resources = "/input_file.json")
void testWithCsvFileSource(String expected_output, String input_date, String output_format, String default_value, String exception_handling) {
           assertEquals(expected_output, myLogic(input_date,output_format,default_value,exception_handling));
}

Sample Json

    {
"1":{
    "expected_output": "bad_date",
    "input_date": "112321",
    "output_format": "",
    "default_value": "",
    "exception_handling": ""
},
"2":{
    "expected_output": "bad_date",
    "input_date": "112322",
    "output_format": "",
    "default_value": "",
    "exception_handling": ""
},
"3":{
    "expected_output": "bad_date",
    "input_date": "112323",
    "output_format": "",
    "default_value": "",
    "exception_handling": ""
},
"4":{
    "expected_output": "bad_date",
    "input_date": "112324",
    "output_format": "",
    "default_value": "",
    "exception_handling": ""
}
}

How do I implement the Page Object Pattern C# Code described below with selenium?

I need to implement the following Page Object Pattern C# Code with selenium. https://www.automatetheplanet.com/page-object-pattern/

Inside one of the examples; there is some code-

   [FindsBy(How = How.Id, Using = "sb_form_q")]
    public IWebElement SearchBox { get; set; }

If I were to run some tests with the following code how would I use the code pattern with id, classes, values from a website. etc? Can someone give examples?

How to perform Spring Rest controller testing using same test class with different data?

I am currently trying to write very simple integration tests for my Spring REST controllers.

Lets say my test class looks something like this:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class RealNewTest2 {

    @Autowired
    private MockMvc mvc;

    @Test
    public void test() throws Exception {
        mvc.perform(
                get(GET_URL).
                with(httpBasic("user","pass"))).
        andExpect(status().isOk());


        System.out.println("Test done.");
    }

}

I want to perform very basic test case that would test all the calls(GET,POST,PUT,DELETE) etc. All of my REST controllers are very alike. The goal that I am thinking is that I would have test data for all controllers like the JSON object that it uses when doing PUT test and then it would have the URL/Mapping that the controller uses. All of my controllers Mappings are the same expect the last part for example mysite/accounts and mysite/countries.

So is there any way that i could write one test case that would perform all of these REST calls and then just run it again with different url and JSON object so i wouldn't have to write so many test cases since they are only VERY basic tests and are basically exactly the same expect for the JSON object and REST URL.