samedi 31 août 2019

Serialize and Cache return values from function and playback snapshot of results

Foo is an example of a function that works "now" but in the future it will possibly throw an error or return some different value.

const foo = () => {
  if (new Date() < new Date('2019-09-05') {
     return 'Hello world"
  }
  throw new Error('failure')
}

const x = cacheLock(foo())

What I am looking for is a way to wrap the return value of foo() so that If a value is returned successfully on initial execution it will cache a snapshot of the result to a file locally and on subsequent executions of this code the stored value is automatically returned and the contents of foo() is never run.

I'm looking for a way to serialize functions results as well as async / awaited promises locally, then playback the stored results.

An ideal feature would be a way to also re-run the code and update the cache.

Is this possible? I know there are issues when it comes to serializing objects and using .toJSON() .fromJSON() methods is one way to solve that.

Are there any libraries out there that can do this? Is there a means of achieving this without serialization?

I'd love a generic solution to this problem that's not tied to testing, or databases. But my top use case is easily mocking / stubbing API calls and Database reads. The sources of which can change with time and aren't reliable to run in tests. There are many solutions when it comes to those mocking databases or mocking api calls, but I would find that some way to cache live calls, and store them for later the most intuitive.

This idea is more of a post-runtime memoization, a cache that sustains even when the process is finished, while traditional memoization just lasts within the runtime of a process.

Jest, how to ignore test coverage of specific folders?

In my react project I have a root ./styles folder which contains various style objects for styled-components. I do not want these files to show up in the coverage test.

I've tried to hide them like so, but when I run npm run coverage they still show up.

enter image description here

package.json

"jest": {
  "setupFilesAfterEnv": [
    "<rootDir>/jest.setup.js"
  ],
  "coveragePathIgnorePatterns": [
    "<rootDir>/styles/",
    "./styles/"
  ],
  "testPathIgnorePatterns": [
    "<rootDir>/.next/",
    "<rootDir>/node_modules/",
    "<rootDir>/styles/",
    "./styles/"
  ],
  "transform": {
    "^.+\\.(js)$": "babel-jest",
    "^.+\\.js?$": "babel-jest",
    "^.+\\.ts?$": "babel-jest",
    "^.+\\.tsx?$": "babel-jest",
    "^.+\\.json5$": "json5-jest"
  },
  "moduleFileExtensions": [
    "js",
    "json",
    "json5",
    "ts",
    "tsx"
  ],
  "modulePaths": [
    "<rootDir>/components/",
    "<rootDir>/pages/",
    "<rootDir>/shared/"
  ]
}

babelrc

{
  "env": {
    "development": {
      "presets": [
        "next/babel",
        "@zeit/next-typescript/babel"
      ],
      "plugins": [
        ["styled-components", {"ssr": true, "displayName": true}],
        ["@babel/plugin-proposal-decorators", {"legacy": true}],
        ["istanbul",{"exclude": ["styles/*.js"]}]
      ]
    },
    "production": {
      "presets": [
        "next/babel",
        "@zeit/next-typescript/babel"
      ],
      "plugins": [
        ["styled-components", {"ssr": true, "displayName": true}],
        ["@babel/plugin-proposal-decorators", {"legacy": true}]
      ]
    },
    "test": {
      "presets": [
        "@babel/preset-typescript",
        ["next/babel", {"preset-env": { "modules": "commonjs" }}]
      ],
      "plugins": [
        ["styled-components", { "ssr": true, "displayName": true }],
        ["@babel/plugin-proposal-decorators", { "legacy": true }],
        ["babel-plugin-sass-vars"]
      ]
    }
  }
}

Testing component snapshot, getting json error

Started on a snapshot test because I want to cover testing my react styled-components.

Expected

Wrote a basic snapshot test, test should pass and generate snapshot

Results

For some reason test is failing due to checking my coinStyles.json file:

SyntaxError: /Users/leongaban/projects/Futuratum/moon.holdings/coinStyles.json: Unexpected token, expected ";" (2:7)

      1 | {
    > 2 |   "ada": {
        |        ^
      3 |     "color": "#FFF",
      4 |     "backgroundColor": "#6297DF"
      5 |   },


Not sure why coinStyles.json is being hit, it's used in my utils/modifiers file which isn't touched by the about.tsx file.

Branch in question:

https://gitlab.com/futuratum/moon.holdings/tree/tests-completion

Merge Request:

https://gitlab.com/futuratum/moon.holdings/merge_requests/6

The About component

import React from 'react'

import { Astronaut, NomicsLink } from '../components'
import { AboutContainer, TeamImages, TeamImg, TeamDiv, TeamSocial } from '../styles'
import { MOON_HOLDINGS } from '../shared/constants/copy'

class About extends React.Component {
  render() {
    return (
      <div id="about-container">
        <AboutContainer>
          <h1>The Futuratum Team</h1>
          <p><a href="https://futuratum.io">Futuratum</a> is about building, playing and exploring possibilities within the nascent cryptocurrency space.</p>
          <p>Questions we ask ourselves everyday: What is worth building? What are the possible emerging trends? What fintech solutions could help people best? How could we gamify finance and building wealth?</p>
          <TeamImages>
            <TeamDiv>
              <TeamImg src="static/team/leon.png" alt="Leon Gaban"/>
              <h4>Leon Gaban</h4>
              <h5>Founder</h5>
              <TeamSocial>
                <a href="https://twitter.com/leongaban" target="_blank" title="Leon on Twitter">
                  <img src="static/twitter.png" alt="Leon's Twitter"/>
                </a>
                <a href="https://github.com/leongaban" target="_blank" title="Leon's Github">
                  <img src="static/github.png" alt="Leon's Github"/>
                </a>
              </TeamSocial>
              <p>Leon Is a UI developer who comes from a design background, a self-taught coder with a passion for educating people about cryptocurrencies.</p>
            </TeamDiv>
            <TeamDiv>
              <TeamImg src="static/team/paulo.png" alt="Paulo Darocha"/>
              <h4>Paulo Darocha</h4>
              <h5>CTO</h5>
              <TeamSocial>
                <a href="https://github.com/prochafilho" target="_blank" title="Paulo's Github">
                  <img src="static/github.png" alt="Paulo's Github"/>
                </a>
              </TeamSocial>
              <p>Paulo is a self-taught full-stack programmer, with a passion for coding, math, teaching code and constant learning.</p>
            </TeamDiv>
          </TeamImages>
          <p>Our first product is <span>{MOON_HOLDINGS}</span>, a web UI based cryptocurrency portfolio tracker. And we have a roadmap to introduce user accounts and adding gamified ranking elements to growing your crypto wealth.</p>
        </AboutContainer>
        <NomicsLink displayAboutLink={false} />
        <Astronaut className="astronaut" showLogo={true}/>
      </div>
    )
  }
}

export default About

The About test

import React from 'react'
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'

// @ts-ignore (works with .tsx)
import About from '../about.tsx'

describe('<About /> component', () => {
  describe('rendering', () => {
    const wrapper = shallow(<About />);
    it('should render a component matching the snapshot', () => {
      const tree = toJson(wrapper);
      expect(tree).toMatchSnapshot();
      expect(wrapper).toHaveLength(1);
      expect(wrapper.contains(<About/>));
    });
  });
});

vendredi 30 août 2019

Citrus Java DSL store test variable extracted from SQL select query

How do I save the extracted variable expression “orderStatus” into a variable that can be accessed in a receive action? So far, I can only access the variable by overriding the doexecute method in an abstract test action but I cannot access it outside that method..

I am trying to extract “orderstatus” from the select query and then store it in a String variable so I can then access it in the receive action to define an endpoint but am struggling.

I am writing java citrus integration test cases using a junit4testdesigner...

query(dataSource) .statement("select STATUS from ORDERS where ID='${orderId}'") .extract("STATUS", "orderStatus");

Any help would be great

Testing 400 status code axios throws error

I'm creating an api test framework for a project I am working on and I'm looking to validate required fields in JSON objects being sent to an endpoint.

I'm trying to send a JSON object with a missing field and expecting a 400 response from my application with a validation message. But when making this call with axios it (somewhat rightly) throws an error as it received the 400.

I want to be able to assert that 400 is expected and to assert on the validation message.

All the examples I've come across are all regarding dealing with the 400 response in the correct way you would if you are not expecting the 400 response, but i am expecting it.

I couldn't seem to find anyone else trying this.

async function createReminder(reminderObject) {
  const response = await axios.post(`${config.get('baseUrl')}/reminder`, {
    ...reminderObject
  });

  return response;
}

module.exports.createReminder = createReminder;

Here is my working code as it stands. This will make a valid 200 when being used with a valid call.

I need to have the 400 response / validation message be returned in teh response object to be handled in the function that calls this function.

Test for `pester` version using `pester`

I have a set of pester tests for a PowerShell module which use the v4.0+ should operator -FileContentMatch. When these tests are run on a machine with an earlier v3.x version of pester, there is a wave of error messages, none of which exactly point out the problem.

I'd like to write a simple pester test to check for a minimum version and print an explanation / fix for the user / tester.

The extra complication is that pester can be run directly as a script without being installed as a module on the machine.

I've looked at using $(Get-Module -ListAvailable -name "Pester").version to pull out the pester version, but it only sees the PowerShell-"installed" module, not the currently executing version, which, as noted, could be different.

Some signal passed from pester would be fine, but I don't see that pester provides any meta-information to the test scripts (ie, a version environment variable).

Any thoughts on a solution?

How to mount a component withTheme inside another component withTheme?

I'm trying to build a component wrapped by a ThemeProvider which has a child component that is wrapped by the same ThemeProvider in ReactJS.

So, here is the problem. My first component is A and the second one is B. In that case, both of them are returned wrapped by the same ThemeProvider, so I use withTheme(A) and withTheme(B) inside of both.

When I try to debug() those components inside the unit test, I got the content of the component A but I can't get the content of the B component. Why? And how can I do that?

Laravel Testing API Endpoint - POST Parameters Missing

I have a API endpoint that I wish to test, it receives a POST payload. The endpoint basically invokes the Omnipay Sage Pay library to handle a Server Notification.

I can POST to this endpoint using Postman client fine, but when using a Laravel phpunit test e.g.

$response = $this->post($url, $data);

The Omnipay library can't see the post data?

I think this is because the Laravel helper $this->post doesn't use application/x-www-form-urlencoded POST requests? I took a look behind the scenes at $this->post and it seems to invoke the controllers/methods directly which makes sense..

The closest I got to this working was using Guzzle directly (See below), however this routes the request outside of the 'testing' session and back into my local application I'm assuming? This then breaks my tests as I'm setting up some testing data via factories before the POST call.

$response = $client->request('POST', $url, ['form_params' => $data]);

I'm not too sure where the issue lies, either in my tests or the Omnipay library itself?

asserting list of objects in junit testing

I am trying to write a junit test case which compares 2 lists of objects. But the test keeps failing with AssertionError. The assert statement is comparing the object reference and hence the error. I also tried using assertEquals,assertThat and assertArrayEquals. How do I resolve this ? Someone please help me.

Implementing a for loop in systemverilog

I want to generate an automated input stimulus for my DUT. This input is going to different modules at the same time and working on this data. I want my input to be generated in an increasing manner. Like 0000,0001,0010,0011...1111 I tried using a for loop but what it does is only uses the last data from the loop and works on that.

always_comb begin 

for (i=0, i<16; i=i+1) begin data <= i; end end

Xcode keeps converting my app to the default Xcode project

I am trying to open an app to work on. But Xcode keep converting my app to the default project (integration app). It does not open my app. It changes my app name to integration app. I have install my app on my phone and installed app.ipa in the MacBook as well and given the path in the capabilities. I don't know if I have to change any type of setting in the Xcode default WebDriverAgent project.

Test LiveData and Coroutines using MockK

I have this view model:

class MyViewModel(private val myUseCase: MyUseCase) : ViewModel() {

    val stateLiveData = MutableLiveData(State.IDLE)

    fun onButtonPressed() {
        viewModelScope.launch {
            stateLiveData.value = State.LOADING
            myUseCase.loadStuff() // Suspend
            stateLiveData.value = State.IDLE
        }
    }
}

I'd like to write a test that checks whether the state is really LOADING while myUseCase.loadStuff() is running. I'm using MockK for that. Here's the test class:

@ExperimentalCoroutinesApi
class MyViewModelTest {

    @get:Rule
    val rule = InstantTaskExecutorRule()

    private lateinit var myUseCase: MyUseCase
    private lateinit var myViewModel: MyViewModel

    @Before
    fun setup() {
        myUseCase = mockkClass(MyUseCase::class)
        myViewModel = MyViewModel(myUseCase)
    }

    @Test
    fun `button click should put screen into loading state`() = runBlockingTest {
        coEvery { myUseCase.loadStuff() } coAnswers  { delay(2000) }
        myViewModel.onButtonPressed()
        advanceTimeBy(1000)
        val state = myViewModel.stateLiveData.value
        assertEquals(State.LOADING, state)
    }
}

It fails:

java.lang.AssertionError: 
Expected :LOADING
Actual   :IDLE

How can I fix this?

How to test mysql insert method

I'm setting up testing in Go. I use go-sqlmock to test mysql connection. Now I try to test mysql insert logic. But the error occurs.
I want to know how to resolve this error.

server side: golang
db: mysql
web framework: gin

dao.go

func PostDao(db *sql.DB, article util.Article, uu string) {
    ins, err := db.Prepare("INSERT INTO articles(uuid, title,content) VALUES(?,?,?)")
    if err != nil {
        log.Fatal(err)
    }
    ins.Exec(uu, article.TITLE, article.CONTENT)
}

dao_test.go

func TestPostArticleDao(t *testing.T) {
    db, mock, err := sqlmock.New()

    if err != nil {
        t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
    }

    defer db.Close()

    mock.ExpectExec("^INSERT INTO articles*").
        WithArgs("bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c", "test", "test").
        WillReturnResult(sqlmock.NewResult(1, 1))

    article := util.Article{
        ID:      1,
        TITLE:   "test",
        CONTENT: "test",
    }

    PostDao(db, article, "bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c")

    if err := mock.ExpectationsWereMet(); err != nil {
        t.Errorf("there were unfulfilled expections: %s", err)
    }
}

I expect go test -v runs without error.
But the actual is not.
Here is the error.

=== RUN   TestPostArticleDao
2019/08/31 00:08:11 call to Prepare statement with query 'INSERT INTO articles(uuid, title,content) VALUES(?,?,?)', was not expected, next expectation is: ExpectedExec => expecting Exec or ExecContext which:
  - matches sql: 'INSERT INTO articles(uuid, title,content) VALUES(?,?,?)'
  - is with arguments:
    0 - bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c
    1 - test
    2 - test
  - should return Result having:
      LastInsertId: 1
      RowsAffected: 1
exit status 1
FAIL    article/api/dao 0.022s

Android on device testing doesn't work anymore, used to

TLDR: on device app testing doesn't work anymore, used to perfectly.

I'm currently writing an android app, not a super complicated one, just a small one with text to get the hang of it. Since I have an old AMD cpu, I can't use the emulator, so I test on my phone. Everything worked perfectly, I could see my main menu, until I added a second java class/activity: the app builds with success, gets transfered to my phone, I get either a blank screen or it prompts me to the usual security "are you sure you want to run it?" before giving my a blank screen. I don't understand, it worked perfectly and quite well, I could use the app, type text etc, but now I can't even run it... also, when I go back on my homescreen and try to tap on my app icon, which used to work, it just spashes a blank screen, again.

I tried uninstalling my app and reinstalled it, did not work. Restarted android studio, my machine and the phone, did not work. I removed dev mode on my phone before putting it back on, same, did not work.

IDK if it's important, but since I'm learning/in the building process, all the UI elements (e.g textviews, textedits, buttons etc) are laid out BUT not all of them are referenced in the java code.

Thanks a lot.

How to fix: java.lang.ClassNotFoundException: BasicSimulation for gradle gatlingRun task?

I'm trying to run a gatling task via gradle. I specifically set my scala sourceCode set, run compileScala befor running gatlingRun, but I keep on getting an error: java.lang.ClassNotFoundException: BasicSimulation

How do I set up te task properly? The build.gradle:

plugins {
    id "com.github.lkishalmi.gatling" version "3.0.2"
}
repositories {
    mavenCentral()
}
apply plugin: 'java'
apply plugin: 'scala'

sourceSets {
    main {
        scala {
            srcDirs = ['src/gatling/simulations/']
        }
    }
}



dependencies {
    compile "io.gatling:gatling-core:3.0.2"
    compile "io.gatling:gatling-http:3.0.2"
    compile 'io.gatling.highcharts:gatling-charts-highcharts:3.0.2'
    compile 'org.scala-lang:scala-library:2.11.8'
    testCompile "io.gatling:gatling-core:3.0.2"
    testCompile "io.gatling:gatling-http:3.0.2"
    testCompile 'io.gatling.highcharts:gatling-charts-highcharts:3.0.2'

}

gatling {
    simulations = {
        include "*.scala"
    }
}



Gradle syntax: gradlew compileScala gatlingRun -Dorg.gradle.java.home=C:\Users\saber.alex\Documents\jre1.8.0_91

Error:


> Task :gatlingRun
16:22:52.131 [main] INFO io.gatling.core.config.GatlingConfiguration$ - Gatling will try to use 'gatling.conf' as custom config file.
16:22:52.910 [GatlingSystem-akka.actor.default-dispatcher-2] INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger started
16:22:54.045 [main] ERROR io.gatling.app.Gatling$ - Run crashed
java.lang.IllegalArgumentException: User defined Simulation class BasicSimulation could not be loaded
    at io.gatling.app.Selection$Selector.findUserDefinedSimulationInClassloader$1(Selection.scala:79)
    at io.gatling.app.Selection$Selector.$anonfun$singleSimulationFromConfig$4(Selection.scala:84)
    at scala.Option.orElse(Option.scala:289)
    at io.gatling.app.Selection$Selector.$anonfun$singleSimulationFromConfig$3(Selection.scala:84)
    at scala.Option.flatMap(Option.scala:171)
    at io.gatling.app.Selection$Selector.singleSimulationFromConfig(Selection.scala:82)
    at io.gatling.app.Selection$Selector.$anonfun$selection$1(Selection.scala:52)
    at scala.Option.getOrElse(Option.scala:121)
    at io.gatling.app.Selection$Selector.selection(Selection.scala:44)
    at io.gatling.app.Selection$.apply(Selection.scala:36)
    at io.gatling.app.Runner.run0(Runner.scala:74)
    at io.gatling.app.Runner.run(Runner.scala:61)
    at io.gatling.app.Gatling$.start(Gatling.scala:74)
    at io.gatling.app.Gatling$.fromArgs(Gatling.scala:47)
    at io.gatling.app.Gatling$.main(Gatling.scala:39)
    at io.gatling.app.Gatling.main(Gatling.scala)
Caused by: java.lang.ClassNotFoundException: BasicSimulation
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at io.gatling.app.Selection$Selector.$anonfun$singleSimulationFromConfig$2(Selection.scala:70)
    at scala.util.Try$.apply(Try.scala:209)
    at io.gatling.app.Selection$Selector.findUserDefinedSimulationInClassloader$1(Selection.scala:70)
    ... 15 common frames omitted

> Task :gatlingRun FAILED
3 actionable tasks: 3 executed

Thanks before.

Cypress, read the data from API response

All of the example I found are with calling the API and defining method and URL. For example

  cy.server()

  cy.route({
    method: 'GET',
    url:'https://www.something.com, 
    }).as('get_jobs')

  cy.get('[data-cy="job-search-input"] button').click()

  cy.wait('@get_jobs').then((xhr) => {
     cy.log(xhr.response.body.data)
  })

What I want is just to select the button, press click and read the response that it gives me. I don't wanna define url again, but use the one that is already used in the code and just check the response that it gives me after pressing the button.

How can I do that?

How to add variable to URL in jmeter

Im am currently creating a automated test in jmeter but i cant seem to add a variable to the URL in the same way i can add it to a body.

So for instance in step two of my test i use the json extractor to create a variable called gamecode which i then apply to the next GET request:

https://game.oyster.com/api/v1/games/${gameCode}

but the request isnt changing the ${gameCode} to the actual numeber its just remaining in its current form, the gameCode varible is working in the body of requests later on in the code i cant figure out how to add it to the url

Extract a string from Response Body in Jmeter

I am trying to set up an automated test in jmeter. However I am having a problem extracting a string from an array of numbers that are returned from an api call.

Currently Im recieving [1069936,1069931,1038673,1059014,1061326,1074842,1076998,1069605,1060567,1063853,2021064,2024239,1074835,1075227,1076997,1078435] but i would like to extract "1069936" and use it in the next api call. Ive tried -1 in the Match No. column of the Json Extractor but cant find any documentation to help.

Where to write testcases for mobile apps

I am a tester, but putting my hands on in Android app development and have developed a EdTech app "Class eLearn Mobile app"

As of now, i am manually testing the application and pushing the updates to production.

But now i want to write automated cases in the same development project and implement CI/CD or DevOps. How can we do that? I know in Maven projects, we can have a separate test folder, where we can write functional tests. How can i do the same with Android apps?

Your inputs are highly appreciated.

How do I mock ApolloMutation component?

Everything about the app works fine except the testing.

I have tried to use mount and shallowMount methods exposed by @vue/test-utils to mock the ApolloMutation component.

I have seen couple of solutions on VueApollo testing. I have tried this. In my case, I'm using NuxtApollo community module. I tried to apply it the same way, but throwing error about the wrapper been empty, not sure if importing the @nuxtjs/apollo is the right thing to do.

import { createLocalVue, shallowMount } from '@vue/test-utils'
import VueApollo from '@nuxtjs/apollo'
import Register from '../pages/register/index.vue'

describe('Register user', () => {

  let localVue
  beforeEach(() => {
    localVue = createLocalVue()
    localVue.use(VueApollo, {})
  })

  it('Should click the register button to register', () => {

    const mutate = jest.fn()
    const wrapper = shallowMount(Register, {
      localVue,
      mocks: {
        $apollo: {
          mutate,
        }
      }
    });

    wrapper.find('.callMe').trigger('click')
    expect(2+2).toBe(4)
  });
});

The component I want to test.

<template>
  <ApolloMutation
      :mutation="require('../../apollo/mutations/createUser.gql')"
      :variables="{firstName, lastName, username, phone, email, password}"
      @done="onDone">
    <template v-slot="{ mutate, loading, error }">
      <input v-model="firstName" placeholder="first name">
      <input v-model="lastName" placeholder="last name">
      <input v-model="username" placeholder="username">
      <input v-model="phone" placeholder="phone">
      <input v-model="email" placeholder="email">
      <input v-model="password" placeholder="password">
      <button :disabled="loading" @click="mutate">CreateUser</button>
      <button class="callMe" @click="callMe">CreateUser</button>
      <p v-if="error">An error occurred: </p>
      <p v-if="loading">loading...</p>
    </template>
  </ApolloMutation>
</template>

I expected the output to be 4 but I got the error: [vue-test-utils]: find did not return .callMe, cannot call trigger() on empty Wrapper

How to add types checker for the Jest in the TypeScript app?

I need to add some type checker to the Jest. It must look somehow like expect(someVar).toBeType('string') and expect(someVar).toBeType(['string', 'object']).

I tried to add some checker-helper, but it looks a little bit ugly.

const toBeType = (arg:any, type:string) => {
    const argType = typeof arg;

    if (argType !== type)
        throw new Error(`Expected '${type}' but got '${argType}' for 'arg'.`);
};

I want to add similar functionality to the jest namespace to have ability to call type checker like expect(someVar).toBeType('boolean').

How to test API webhooks with selenium and java

I wolud like to test API webhooks. I have website where i can put https address(webhook) and then i will get information about stock and prices of products. How to do automation? The problem is webhook website. I can use something like https://webhook.site and then read data from this page. But it's external page - sometimes it can work or not. Is it good resolving? If not...how to do better?

jeudi 29 août 2019

Create testable examples for objects that implements interfaces

According to the GoLang document, you can write examples for a piece of code. See https://blog.golang.org/examples for more information.

I have the following method:

// StdOutSink is a 'log.Sink' implementation which logs to 'StdOut'.
type StdOutSink struct {
}

// Write prints a message to 'StdOut'.
func (s StdOutSink) Write(msg message) {
    fMsg := fmtMsg(msg)

    fmt.Printf("%v\n", fMsg)
}

And I would like to make a testable example for this, which is done with the following code:

// Ensures the correct implementation of the 'Write' method.
func ExampleWrite() {
    // Arrange.
    s := new(StdOutSink)

    // Act.
    s.Write(createMessage(traceS, "Message"))
    s.Write(createMessage(debugS, "Message"))
    s.Write(createMessage(infoS, "Message"))
    s.Write(createMessage(warnS, "Message"))
    s.Write(createMessage(errorS, "Message"))
    s.Write(createMessage(fatalS, "Message"))

    // Output:
    // [TRACE]: Message
    // [DEBUG]: Message
    // [INFO]: Message
    // [WARNING]: Message
    // [ERROR]: Message
    // [FATAL]: Message
}

// PRIVATE: createMessage returns a 'log.message' with the given severity and text.
func createMessage(s severity, txt string) message {
    msg := new(message)
    msg.severity = s
    msg.text = txt

    return *msg
}

This all works, the tests are being executed, but go-vet is given me the following message:

`ExampleWrite refers to unknown identifier: Write`

How should I name my example method so that it's linked to the function func (s StdOutSink) Write(msg message)

Is there a way to do flutter widget test on pie-carts?

I am doing a flutter widget test for a mobile app , one of the page contains a pie-chart. I need to create the widget test for this pie-chart and later compare it with the golden image to see that the pie-chart is working as expected. But i could not find anywhere how to create a widget test for the pie-chart. I am also not able to capture the actual pie-chart on the golden image , whereas rest all elements are being displayed on the golden image.

I have created the widget test and golden image for the whole page and it is able to capture everything but not the pie-chart.

Code for pie-chart :

return Container(
  height: 175.0,
  child: Stack(
    children: <Widget>[
      // container for the pie chart
      Container(
        key: const Key('graphFigure'),
        child: charts.PieChart<String>(
          pieChartData,
          animate: true,
          // arcWidth variable decides with size of the pie pieces in the chart
          defaultRenderer:
              charts.ArcRendererConfig(arcWidth: AppDimen.graphArcWidth),
        ),
      ),

code for widget test :

final Finder graphFigure = find.byKey(Key('graphFigure'));
  final Finder irpercentageValueInGraph = find.byKey(Key('percentageValueInGraph'));
  final Finder pcSignInGraph = find.byKey(Key('percentageSignInGraph'));

expect(getGraphFigure(), findsOneWidget, reason: 'The Pie Chart is not visible');
expect(getIRPercentageValueInGraph(), findsOneWidget, reason: 'The In Range percentage value inside the graph not visible');
expect(getPcSignInGraph(), findsOneWidget, reason: 'Percentage sign inside the graph not visible');

Generating input for module

I wish to send different input data to a module that injects error in the data and sends it to the decoder. The following module works when I give one input data. But when I give more than 1 input data stream, this module only works on the last data stream.

module error_inject (data_in, parity_in, data_out, parity_out, idx_to_flip);

parameter DATA_WIDTH = 13; 
parameter IDX_WIDTH = $clog2(DATA_WIDTH);

input [7:0] data_in;
input [4:0] parity_in;
output reg [7:0] data_out;
output reg [4:0] parity_out;
int i;

output reg [IDX_WIDTH-1:0] idx_to_flip;
reg [DATA_WIDTH-1:0] int_data;

always@(data_in)
begin 

for (i=0;i<20;i=i+1)
begin 
int_data = {data_in, parity_in};

idx_to_flip = $urandom_range(DATA_WIDTH-1);
$display("Flipping data bit %d", idx_to_flip);

int_data[idx_to_flip] = !int_data[idx_to_flip];
$display("bad data = %b",int_data);

 data_out = int_data[12:5];

 parity_out = int_data[4:0];

#60;
end 

end 

endmodule

I want the module to iterate over every input data that I provide through the testbench.

Spree test rspec Failure/Error: expecting <"new"> but rendering with <[]>

I've been trying to pass this test suite on our spree app but it keeps saying:

Failure/Error: expect(response).to render_template(:new)
       expecting <"new"> but rendering with <[]>

here's the test:

context 'New action' do
    it 'render view new template' do
      spree_get :new
      expect(response).to render_template(:new)
    end
  end

what's weird is when I test this code it passes, theyre basically the same:

context 'Index action' do
    it 'render view index template' do
      spree_get :index
      expect(response).to render_template(:index)
    end

    it 'index should have a status code of 200', focus: true do
      spree_get :index
      expect(response.status).to eq(200)
    end
  end

also tried adding render_views doesn't work. I also followed the instruction on this link spree_test still no luck. I also run it many times without touching the code hoping that it will work nothing happens. Also tried praying still no chance.

Additional Information

spec/support/spree_controller_request.rb

require 'spree/testing_support/controller_requests'

RSpec.configure do |config|
  config.include Spree::TestingSupport::ControllerRequests, :type => :controller
  config.include Devise::TestHelpers, :type => :controller
end

spec/spec_helper.rb

# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.

ENV['RAILS_ENV'] = 'test'
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'capybara/rspec'

RSpec.configure do |config|
  # rspec-expectations config goes here. You can use an alternate
  # assertion/expectation library such as wrong or the stdlib/minitest
  # assertions if you prefer.
  config.expect_with :rspec do |expectations|
    # This option will default to `true` in RSpec 4. It makes the `description`
    # and `failure_message` of custom matchers include text for helper methods
    # defined using `chain`, e.g.:
    #     be_bigger_than(2).and_smaller_than(4).description
    #     # => "be bigger than 2 and smaller than 4"
    # ...rather than:
    #     # => "be bigger than 2"
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  # rspec-mocks config goes here. You can use an alternate test double
  # library (such as bogus or mocha) by changing the `mock_with` option here.
  config.mock_with :rspec do |mocks|
    # Prevents you from mocking or stubbing a method that does not exist on
    # a real object. This is generally recommended, and will default to
    # `true` in RSpec 4.
    mocks.verify_partial_doubles = true
  end

  # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
  # have no way to turn it off -- the option exists only for backwards
  # compatibility in RSpec 3). It causes shared context metadata to be
  # inherited by the metadata hash of host groups and examples, rather than
  # triggering implicit auto-inclusion in groups with matching metadata.
  config.shared_context_metadata_behavior = :apply_to_host_groups

  # The settings below are suggested to provide a good initial experience
  # with RSpec, but feel free to customize to your heart's content.
  begin
    # This allows you to limit a spec run to individual examples or groups
    # you care about by tagging them with `:focus` metadata. When nothing
    # is tagged with `:focus`, all examples get run. RSpec also provides
    # aliases for `it`, `describe`, and `context` that include `:focus`
    # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
    # config.filter_run_when_matching :focus

    # Allows RSpec to persist some state between runs in order to support
    # the `--only-failures` and `--next-failure` CLI options. We recommend
    # you configure your source control system to ignore this file.
    # config.example_status_persistence_file_path = "spec/examples.txt"

    # Limits the available syntax to the non-monkey patched syntax that is
    # recommended. For more details, see:
    #   - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
    #   - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
    #   - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
    config.disable_monkey_patching!

    # Many RSpec users commonly either run the entire suite or an individual
    # file, and it's useful to allow more verbose output when running an
    # individual spec file.
    # if config.files_to_run.one?
      # Use the documentation formatter for detailed output,
      # unless a formatter has already been configured
      # (e.g. via a command-line flag).
      # config.default_formatter = "doc"
    # end

    # Print the 10 slowest examples and example groups at the
    # end of the spec run, to help surface which specs are running
    # particularly slow.
    # config.profile_examples = 10

    # Run specs in random order to surface order dependencies. If you find an
    # order dependency and want to debug it, you can fix the order by providing
    # the seed, which is printed after each run.
    #     --seed 1234
    config.order = :random

    # Seed global randomization in this process using the `--seed` CLI option.
    # Setting this allows you to use `--seed` to deterministically reproduce
    # test failures related to randomization by passing the same `--seed` value
    # as the one that triggered the failure.
    Kernel.srand config.seed
  end
end

spec/rails_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)

require 'rspec/rails'
require 'capybara/rails'
# require 'capybara/rspec'
# Add additional requires below this line. Rails is not loaded until this point!

# 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 }

# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
RSpec.configure do |config|
  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # FactoryBot
  config.include FactoryBot::Syntax::Methods

  # Database Cleaner
  # source: http://www.virtuouscode.com/2012/08/31/configuring-database_cleaner-with-rails-rspec-capybara-and-selenium/
  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = false
  config.before(:suite) do
    # RAILS_ENV and Rails.env can be different at times; fail if any of the two is different
    abort("The Rails environment is not running in test mode!") if !Rails.env.test? || ENV['RAILS_ENV'] != 'test'

    # Prevent database truncation if the environment is not test
    DatabaseCleaner.clean_with(:truncation)
  end
  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end
  config.before(:each, js: true) do
    DatabaseCleaner.strategy = :truncation
  end
  config.before(:each) do
    DatabaseCleaner.start
  end
  config.after(:each) do
    DatabaseCleaner.clean
  end
  # when testing methods with transactions, we have to manage commits / rollbacks manually (ex: option_type_generator_spec.rb):
  # 1. Add testing_transactions: true to the example call
  #    - this tells database_cleaner to NOT wrap the example in a transaction (we'll manage the test and cleanup ourselves)
  # 2. Wrap the test logic inside a transaction
  #    - make sure that the transaction to be tested allows for nested transactions (requires_new: true)
  # 3. Execute the test sequence and the necessary tests
  # 4. Afterwards, ensure cleanup:
  #    - rollback the test transaction
  #    - after rollback, inspect the data to make sure that test details did not persist
  config.around(:each, :testing_transactions => true) do |ex|
    DatabaseCleaner.strategy = nil
    ex.run
    DatabaseCleaner.strategy = :truncation
  end

  # 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")
end

# Shoulda 
require 'shoulda/matchers'
Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
  end
end

How to test components in React

I have learned to test my code with Mocha and Node and I have no problem with this because always I'm testing functions. But, If I want to test a component which is an object with his constructor, componentDidMount, render functions ... How do you do this tests?

Which is the best way to test this components which are objects?

Any example of how to make this tests?

TempData Empty on Redirect During SpecFlow Tests Only

I'm testing a .Net Core 2.2 web app using SpecFlow, Selenium, and ChromeDriver and am befuddled by something I've encountered.

I'm using TempData to pass data for an alert message between a page that posts data and a page that displays data. When deployed to IIS locally for debugging, etc, I see the TempData until it is consumed and displayed on a page as formatted message. However, I have a step in a SpecFlow scenario that fails when the alert isn't displayed because the TempData is empty. The SpecFlow scenario follows the same steps that are taken during manual testing.

I am testing a .Net Core 2.2 web project from a referenced XUnit/Specflow test project. The following relevant dependencies are used:

  • Microsoft.NetCore.App v2.2.0
  • SpecFlow v3.0.225
  • SpecFlow.xUnit v3.0.225
  • Selenium.WebDriver v3.141.0
  • Selenium.WebDriver.ChromeDriver v76.0.3809.12600

I have confirmed that TempData is populated as expected with the message data when debugging the application locally. Debugging the test shows that TempData is populated upon successful posting of form data but is empty when the resulting OnGet is processed during the redirect.

Here is the post handler for adding an account:

public async Task<IActionResult> OnPostAsync()
{
    if (ModelState.IsValid)
    {
        var user = new IdentityUser { UserName = Account.UserName, Email = Account.EmailAddress };
        var result = await _userManager.CreateAsync(user);

        if (result.Succeeded)
        {

            Dictionary<string, string> SuccessAlert = new Dictionary<string, string>()
            {
                { "Type", "success" },
                { "Title", "Account Added" },
                { "Text",  "Account for user " + Account.UserName + " was added successfully."}
            };

            TempData["Alert"] = SuccessAlert;

            _logger.LogInformation($"account added successfully. Alert title: {SuccessAlert["Title"]}");

            return RedirectToPage("/Accounts/Index", new
            {
                area = "Administration"
            });
        }

        foreach (var error in result.Errors)
        {
            ModelState.AddModelError("", error.Description);
        }

    }

    Dictionary<string, string> ErrorAlert = new Dictionary<string, string>()
            {
                { "Type", "error" },
                { "Title", "Uh-oh!" },
                { "Text",  "Account for user " + Account.UserName + " was not added. See errors below."}
            };

    TempData["Alert"] = ErrorAlert;

    return Page();
}

And the get handler for the /Accounts/Index page that the above redirects to upon successful completion (pretty basic):

public void OnGet()
{
    Accounts = _accountService.FindAll();
    _logger.LogInformation("AccountsIndexModel.OnGet");
    _logger.LogInformation($"Items in TempData: {TempData.Count}");
}

The following are snippets from log files corresponding to the logging in the code above.

Logs for manually adding an account:

2019-08-28 16:18:53.917 -04:00 First.Web.Areas.Administration.Accounts.AddAccountModel [Information] account added successfully. Alert title: Account Added
2019-08-28 16:19:08.587 -04:00 First.Web.Areas.Administration.Accounts.AccountsIndexModel [Information] AccountsIndexModel.OnGet
2019-08-28 16:19:08.588 -04:00 First.Web.Areas.Administration.Accounts.AccountsIndexModel [Information] Items in TempData: 1

And for the SpecFlow automated test:

2019-08-28 17:19:02.014 -04:00 First.Web.Areas.Administration.Accounts.AddAccountModel [Information] account added successfully. Alert title: Account Added
2019-08-28 17:19:02.105 -04:00 First.Web.Areas.Administration.Accounts.AccountsIndexModel [Information] AccountsIndexModel.OnGet
2019-08-28 17:19:02.105 -04:00 First.Web.Areas.Administration.Accounts.AccountsIndexModel [Information] Items in TempData: 0

Here's the SpecFlow scenario:

Scenario: Add new account succeeds
    Given I have access to the "Administration" module
    When I navigate to the "Add Account" page
        And I submit an account with values
            | accountname | emailaddress         |
            | mcullen     | mcullen@mnhockey.com |
    Then I should be on the "Accounts" page
        And I should see a success message with
            | title         | description      |
            | Account Added | Account for user |

And the step definition for the account submission step:

[When(@"I submit an account with values")]
public void WhenISubmitAnAccountWithValues(Table table)
{
    var accountName = "";
    var emailAddress = "";

    var row = table.Rows[0];

    row.TryGetValue("accountname", out accountName);
    row.TryGetValue("emailaddress", out emailAddress);

    _accountsAddPage.AccountNameField.SendKeys(accountName);
    _accountsAddPage.EmailAddressField.SendKeys(emailAddress);

    _accountsIndexPage = _accountsAddPage.Submit();

    _context.Set<string>("Accounts", "currentpage");
}

How to send a request to Opensimulator server

I'm trying to testing a server performance, while the number of users increse, for a CVE system by using OpenSimulator. I thought to send, while bots moving in the CVE, a request to the Server and get its response time. I'm trying to do it with code below:

using System;
using System.Net;

namespace Request
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            WebRequest req = HttpWebRequest.Create("http://externalip:9000/");

            try
            {
                // get the time of a sync request
                var watch = System.Diagnostics.Stopwatch.StartNew();
                WebResponse response = req.GetResponse();
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                //

                long len = response.ContentLength;

                if (len <= 0)
                {
                    Console.WriteLine("ERROR: Got length {0} for {1} {2}", len, req.Method, req.RequestUri);
                }
                else
                {
                    Console.WriteLine("Got length {0} for {1} {2}", len, req.Method, req.RequestUri);
                }
            }
            catch (WebException e)
            {
                Console.WriteLine("ERROR: Got {0} on {1} {2}", e.Status, req.Method, req.RequestUri);
            }
        }
    }
}

But i noticed that it work only with request to a specific resource. So I thought two possibility:

  • Find a uri to request a resource, like a texture

  • Find a way to send a generic request to the server

How can i implement one of these solutions? Any other suggestions?

Jest mock pdfmake and fs.createWriteStream

I am very new to Jest and unit testing in general. I am trying to generate test for a piece of code that essentially uses pdfmake and fs.createWriteStream in order to create and write to a pdf file

As I am reading tutorials - and getting confused a bit as it's info I am not used to - I have tried to put together couple of things. An fs.js module to try and get the writestream mocked. About the pdfmake I am not very sure - could i perhaps skip that and assume I have a target file and therefore mock just the stream creation?

describe('createWriteStream', () => {
  const MOCK_FILE_INFO = {
    '/path/to/file1.pdf': 'console.log("file1 pdf contents");'
  };

Something like the above?

And then just have a result as success for the fs.createWriteStream?

The original code looks something like:

var pdfDoc = new pdfPrinter({
        Roboto: {
            normal: new Buffer(
                require('pdfmake/build/vfs_fonts.js').pdfMake.vfs['Roboto-Regular.ttf'],
                'base64'
            )
        }
    }).createPdfKitDocument(docDefinition);
    pdfDoc.pipe(fs.createWriteStream(path));
    pdfDoc.end();

I understand is not a lot of info but I guess if someone is very aware of unit testing might know how to best shape this. Thanks

Flutter Test Driver Run All Test

In our Flutter application we have multiple integration tests.
I run them one by one by issuing:

flutter drive --target=test_driver/screenshot.dart

However I can't seem to figure out how to run all integration test inside the test_driver folder?

Android studio physical device

Im trying to test my game on mobile phone using android studio. When I run app(button in android studio), on the connected device it shows me error. I attach the images with error and my android studio project.

Second thing is, where i have to drop phaser.min.js and my images from game? into asset folder where html, css, js is?

enter image description here enter image description here

How to wait toast to showed up

I would like to create androidTest for my app. I've started with the login module witch contains multiple fragments and end with a new activity (in another module).

The last screen of login module start a CoroutineWorker to fetch data from our API. The user can see the progress of the worker through a notification. At the end of the worker (takes 30s to 5min), a toast appear with a message : "Success" or "fail"

So, when the test come to the new activity, I would like to wait this toast and check if the message is "Success"

I used this code to check the toast (using UiAutomator and Espresso)


private val uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())

uiDevice.wait(Until.hasObject(By.text("Synchronization finished")), 20000)




For some reason, espresso end the test before the end of the worker, I'm guessing this is because the app is idling but I'm not sure.

SpringBoot unit test cannot load yaml file

when i try to test springboot program, it cannot find application.yaml file.but when i change it to application.properties, it work well.

I tried a lot of methods and couldn't solve the problem very well.It seems that there is only one solution, that is to use the .properties file.

The testCode :

@RunWith(SpringRunner.class)
@SpringBootTest
public class VizServerApplicationTests {

    @Test
    public void contextLoads() {
    }
}

Error Message:

    Could not resolve placeholder 'spring.datasource.url' in value 
    "${spring.datasource.url}"

Testing security configuration - springSecurityFilterChain cannot be null

I am trying to do few tests of my security configuration, specifically test if authenticated user can access a page.

Following this:

https://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test-mockmvc-setup

I have created test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class SecurityConfigTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setUp () {
        mockMvc = MockMvcBuilders
                    .webAppContextSetup(context)
                    .apply(SecurityMockMvcConfigurers.springSecurity())
                    .build();
    }

    @Test
    public void test () {

    }

Configuration:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Override
    public void configure (HttpSecurity security) throws Exception {
        security.formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/knights", true)
                .failureUrl("/login-failure")
                .and()
                .logout()
                .logoutSuccessUrl("/login");

        security.csrf().ignoringAntMatchers("/h2-console/**")
                .and().headers().frameOptions().sameOrigin();

        security.authorizeRequests()
                .antMatchers("/css/**").permitAll()
                .antMatchers("/register").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/h2-console/**").hasAnyAuthority("ADMIN");

        security.authorizeRequests()
                .anyRequest()
                .authenticated();




    }

    @Autowired
    public void securityUsers (AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .passwordEncoder(new BCryptPasswordEncoder())
                .usersByUsernameQuery("SELECT username, password, active FROM player_information WHERE username = ?")
                .authoritiesByUsernameQuery("SELECT username, authority FROM role WHERE username = ?");

    }

}

But I get an exception:

java.lang.IllegalStateException: springSecurityFilterChain cannot be null. Ensure a Bean with the name springSecurityFilterChain implementing Filter is present or inject the Filter to be used.

at org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurer.beforeMockMvcCreated(SecurityMockMvcConfigurer.java:64)
at org.springframework.test.web.servlet.setup.AbstractMockMvcBuilder.build(AbstractMockMvcBuilder.java:137)
at arkpas.kursspring.config.SecurityConfigTest.setUp(SecurityConfigTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
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.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

When I change @WebAppConfiguration to @SpringBootTest it runs fine, but I dont want it to create whole context, because it is much slower.

Go test fails with [build failed] but don't gives a hint what's wrong

I'm running tests and some of them fail with [build failed]. There is no message though, so I don't know what's wrong. Is there a way to configure tests to show build error messages?

$ go test -v ./...
?       badrobot/automation [no test files]
?       badrobot/automation/config  [no test files]
FAIL    badrobot/automation/handlers [build failed]
FAIL    badrobot/automation/middleware [build failed]
?       badrobot/automation/models  [no test files]

Non functional testing for map

Interviewer has question, how you can do non functional testing of map?

I have tried understand google map using and non functional testing?

Django FileField's upload_to not being called during tests

I have a models.py module that looks like this:

def get_path(instance, filename):
    try:
        # Something
    except Exception:
        raise ValidationError("A very specific error message.")

    return f"path/to/{instance.pk}_{filename}"


class FinalDocument(models.Model):
    # ...
    file = models.FileField(upload_to=get_path)

class TempDocument(models.Model):
    # ...
    file = models.FileField()


I have an endpoint that, among other things, grabs a file from a TempDocument instance and assigns it to an existing FinalDocument instance. In real life, this endpoint is failing with "A very specific error message". During tests, however, I cannot for the life of me reproduce this error. I have placed a breakpoint in the upload_to function and it is simply not called. I am assuming this has something to do with different testing vs production settings, but I haven't been able to figure out what. Any idea what I could be missing?

Configuration of SpringJUnit4ClassRunner Test clashes with SpringBootTest

I have a bunch of tests in my project that are all annotated with @SpringBootTest and therefore load up a SpringBoot context.

Now recently I refactored a Test in which I wanted a smaller scope (it´s about process coverage with camunda) to @RunWith(SpringJUnit4ClassRunner.class). Since this means that no context is loaded automatically I create some beans "manually" with a static inner class configuration. The entire test looks something like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
        ExternalConfiguration.class, MyTest.InternalConfiguration.class
})
public class MyTest{

    @Autowired
    private SomeBean someInternalBean;

    @Configuration
    public static class InternalConfiguration{

        @Bean
        SomeBean someInternalBean() {
            return mock(SomeBean .class);
        }

    }
    //Tests

Now, this test runs fine when I run it. BUT when I run any other test ( those still annotated with @SpringBootTest), I get issues with when the ApplicationContext is loaded:

The bean 'someInternalBean', defined in class path resource [.../MyTest$InternalConfiguration.class], could not be registered. A bean with that name has already been defined in file [.../SomeBean.class] and overriding is disabled.

Apparently a bean is created when loading the ApplicationContext because the class is annotated with @Component AND the context loader tries to create another bean from my internal configuration.

I´m hesitant to allow bean-overriding because I´m worried my mock beans might overwrite the automatically created beans.

How do I circumvent this? I want my SpringJUnit4ClassRunner-tests with their internal configurations to not affect my other @SpringBootTest-tests.

data-driven testing vs behavior-driven testing

Let's say I want to automate the testing of a "Login" function, with different usernames and passwords.

What would be the difference between a data-driven test script and a behaviour-driven test script?

Jest: How to mock a promise on the same file for resolve and reject options?

So I am attempting to test the positive and negative sides of my implementation. If I do this:

jest.mock('./apiClient', () => ({
  get: jest.fn((url: string) => Promise.resolve({ data: mockData }))
}));

jest.mock('./apiClient', () => ({
  get: jest.fn().mockImplementation((url: string) => {
    console.log('error result');
    return Promise.reject(mockError);
  })
}));

Then the only test passing will be the last one declared. In the above case, it will be the reject case which will pass and the first mock will be ignored.

This is my whole test:

// @ts-ignore
import ApiClient from './apiClient';
import ApiService from './apiService';

const mockData = {};
const mockError = { message: 'Smth Bad Happened' };

const firstCallback = jest.fn((data: any) => data);
const secondCallback = jest.fn((data: any) => data);

jest.mock('./apiClient', () => ({
  get: jest.fn((url: string) => Promise.resolve({ data: mockData }))
}));

jest.mock('./apiClient', () => ({
  get: jest.fn().mockImplementation((url: string) => {
    console.log('error result');
    return Promise.reject(mockError);
  })
}));

describe('apiService', () => {
  it('should call callbacks consequently', done => {
    ApiService.makeApiCall('testUrl', firstCallback, secondCallback).then(() => {
      expect(firstCallback).toBeCalledTimes(1);
      expect(firstCallback).toBeCalledWith(mockData);

      expect(secondCallback).toBeCalledTimes(1);
      expect(secondCallback).toBeCalledWith(firstCallback(mockData));
      done();
    });
  });

  it('should handle error', done => {
    console.error = jest.fn();
    ApiService.makeApiCall('testUrl', firstCallback, secondCallback).then(() => {
      expect(firstCallback).toBeCalledTimes(0);
      expect(secondCallback).toBeCalledTimes(0);
      expect(console.error).toBeCalledTimes(1);
      expect(console.error).toBeCalledWith('ApiClient testUrl', mockError);
      done();
    });
  });
});

As it is right now, the test passing is should handle error which is the second one, but if I have switch the positions from

jest.mock('./apiClient', () => ({
  get: jest.fn((url: string) => Promise.resolve({ data: mockData }))
}));

jest.mock('./apiClient', () => ({
  get: jest.fn().mockImplementation((url: string) => {
    console.log('error result');
    return Promise.reject(mockError);
  })
}));

To

jest.mock('./apiClient', () => ({
  get: jest.fn().mockImplementation((url: string) => {
    console.log('error result');
    return Promise.reject(mockError);
  })
}));

jest.mock('./apiClient', () => ({
  get: jest.fn((url: string) => Promise.resolve({ data: mockData }))
}));

then the test passing will be should call callbacks consequently, so what can I do to mock both reject and resolve without interfering one with the other?

mercredi 28 août 2019

VBA WITH EXCEL: Copy cell by cell values of one sheet by using loops and paste in another sheet by assigning filter to that Column

Can anyone please help me with the following scenario

1) I have a workbook of sheet1 with two columns and a few rows

2) Applied filter option for sheet1 data

3) Duplicated the sheet1 in the same workbook and renamed it as "Test"

4) Deleted the duplicates in sheet2,column-1 by applying filter

5) Now, I need your help in copying a cell value(the data is dynamic) of sheet2 and paste it in the filtered column-1 of sheet1 so that I can write the comments beside the two columns of sheet1.

**NOTE: DATA IS DYNAMIC

The columns are as below:

SHEET1:

COLUMN-1< <-->COLUMN-2

ABC <--> apple

ABC <--> windows

123 <--> android

ABC <--> os

B <--> phone

123 <--> android

ABC <--> blackberry

ABC <--> apple

B <--> Nokia

ABC <--> Lenovo

SHEET2(This is duplicated sheet):

COLUMN-1<-->COLUMN-2

ABC <--> apple

123 <--> android

B <--> phone

After pasting the copied cell value from 'Test' sheet and pasting it in the filter column-1 of 'Sheet1', the table will be seen like this

Comments also should be added by leaving the first row

STEP-1: (Example: abc)

COLUMN-1<-->COLUMN-2<-->COMMENT

ABC <--> apple <-->

ABC <--> windows <--> same as apple

ABC <--> os <--> same as apple

ABC <--> blackberry <--> same as apple

ABC <--> apple <--> same as apple

ABC <--> lenovo <--> same as apple

STEP-2: (Example: 123)

COLUMN-1<-->COLUMN-2<-->COMMENT

123 <--> android <-->

123 <--> android <--> same as android

STEP-3: (Example: B)

COLUMN-1<-->COLUMN-2<-->COMMENT

B <--> phone<-->

B <--> nokia <--> same as phone

I need the final result to look like this in SHEET1

COLUMN-1<-->COLUMN-2<-->COMMENT

ABC <--> apple<-->

ABC <--> windows <--> same as apple

123 <--> android <-->

ABC <--> os <--> same as apple

B <--> phone <-->

123 <--> android <--> same as android

ABC <--> blackberry <--> same as windows

ABC <--> apple <--> same as apple

B <--> Nokia <--> same as phone

ABC <--> Lenovo <--> same as apple

IT WOULD BE HELPFUL IF YOU CAN HELP ME ASAP.

Katalon: How to fix 'Unable to click on object'?

I'm new to Katalon Studio and currently trying to run some test cases using the software but I'm having an error unable to click on object 'Object Repository/Printing/Page_Dashboard/span_MEDICAL DEVICE REGISTRATION_caret'. One thing I notice this error occur when object name is span_MEDICAL DEVICE REGISTRATION_caret.

Error log

Unable to click on object 'Object Repository/Printing/Page_Dashboard/span_MEDICAL DEVICE REGISTRATION_caret' (Root cause: com.kms.katalon.core.exception.StepFailedException: Unable to click on object 'Object Repository/Printing/Page_Dashboard/span_MEDICAL DEVICE REGISTRATION_caret'

Best way to distribute Flutter application Android & iOS. Best Practices in Flutter Beta Distribution

I'm new in Flutter Development. Friends, please guide me how can I distribute Flutter Application (Both Android & iOS) Beta build. I was going through with Crashlytics Beta Distribution. But I think there is some problem distributing Android & iOS app with same name or ids.

How to debug [object ErrorEvent] thrown in angular/jasmine test cases

In my angular application, we are using jasmine and karma for running test cases. I have several components and it has their test cases written. When I added a new component and wrote test cases they ran successfully when I ran through fdescribe. When I run the whole test suit, I get [object ErrorEvent] thrown on some test case randomly. I don't see any issue with that test case. When I comment that test which it failed for [object ErrorEvent], it gave me the same error on another test case.

I tried to go to DEBUG on KARMA window and see the console, it didn't give me any clue. I tried running ng test --source-map=false, it didn't give me any clue.

  1. Are they any other options to find which test case is exactly causing the issue.
  2. While running ng test is there any option to know from which file the test cases are running, such that when failed I can go and look into the test cases in that file.

What one line code algorithm in python 3 will give such result?

The test question is in the form of a fill in the blanks and this question shows part of the code and requires me to provide the code the programmer must have entered to give the result printed in a single line statement.

a = [1, 2, 3, 4, 5, 6, 2, 4, 1, 7, 8]
#[fill in the blank in one line]
print(a)
#[1, 2, 3, 4, 5, 6 ,7 8]

The result is the list shown rearranged with no duplicates in it.

How to reverse path for custom user when testing Django Rest Framework

I'm building a Django 3 app using a Custom User. I'm trying to test the Custom User, but I can't get the url using reverse. I'm using Django Rest Framework. I'm using Django Rest Auth.

myapp.api.urls.py:

app_name = 'myApp'

from django.urls import include, path, re_path

urlpatterns = [
...
path('users/', include('users.urls'), name='UsersURLS'),
]

myapp.users.urls.py

from django.urls import include, path

from . import api
app_name = 'users' # namespace for reverse
urlpatterns = [
    path('', api.UserListView.as_view(), name='UsersPath'),
]

myapp.users.api.py

class UserListView(generics.ListCreateAPIView):
    queryset = models.CustomUser.objects.all()
    serializer_class = serializers.UserSerializer
    authentication_classes = (TokenAuthentication,)

And in test_users_api.py:

from users.api import UserListView

user_detail_url = reverse('myApp:UsersURLS-list')

...

def test_user_detail(self):
    self.client.force_authenticate(user=self.user)
    response = self.client.post(user_detail_url, {'pk': self.user.id }, format='json')

Whatever I try for the reverse, I get an error that is it not a valid view or function name

reverse('myApp:UsersURLS-list')

reverse('users:UsersPath-list')

reverse(UserListView)

I'd be grateful for any idea what I'm doing wrong, and how to get the reverse URL. I have it working for the rest of my endpoints which use router, but I can't see what's needed for my Custom User, which I set up following a tutorial and it works fine otherwise.

Expect "Object" to receive message not working as expected

I have this spec:

it 'makes a request to google if redis is empty' do
  fetch_cfm_data

  expect(GoogleCalendarApi::V1::Client).to receive(:get_cfm)
end

I've debugged the messages being called during this process of my test and GoogleCalendarApi::V1::Client.get_cfm is certainly being called because I can pry inside of that method during the test run. Why does my test return this failure? -

Failure/Error: expect(GoogleCalendarApi::V1::Client).to receive(:get_cfm)

       (GoogleCalendarApi::V1::Client (class)).get_cfm(*(any args))
           expected: 1 time with any arguments
           received: 0 times with any arguments

How to set up configuration files for a .net core testing project (no ASP.NET)

I'm setting up a testing repository where different developers from different teams will contribute to. Therefore, I need to find a way to store some general configuration and some feature dependent configuration.

The repository I am setting up is using the following technologies / libraries:

  • .NET Core Framework 2.2
  • Specflow to write tests using feature files and step definitions
  • MSTest to run the tests

The basic structure of the repository should be quite simple, there is only one project with two base folders, where one folder is for common code and the other contains a folder for each feature:

  • Project
    • Common
    • Features
      • Feature1
      • Feature2
      • ...

Now I want to have some settings in the common folder (which is maintained by the repository owner) as well as settings for each feature, which are added and maintained by the feature developers:

  • Project
    • Common
      • settings.json
    • Features
      • Feature1
        • settings.json
      • Feature2
        • settings.json
      • ...

The settings should be done in nested json files. Each developer should be able to use access the common settings and his individual feature settings from withiin his code. I'm using a Context Injection from Specflow to inject services into test classes.

My questions are:

How should I set up a proper configuration handling without creating a really configuration mess? There is a lot of documentation online on how to set up a ASP.NET project configuration, but as you see my project setup differs from a common ASP.NET project. There is only ONE environment involved (the testing environment), but a lot of configuration for different features.

What are these numbers in green color represent when testing react component and running test coverage?

I am writing Unit test cases for react components and after successfully implementing the test case. I run code coverage for that particular file.

There is one thing that I noticed which is the numbers written in green color before the statements and branches. I am providing the snapshot of it. So I want to know what this represent.

enter image description here

Enable PSQL hstore extension in Django test db during CI

Context

Some steps of my Continuos Integration procedure are:

  • start Postgres docker container
  • run Django tests

When manage.py test --noinput command is runned it:

  • creates a new test_xxx database (drop if exists)
  • runs the founded migrations against it
  • runs the founded set of tests

Into the tests that need to fetch data from the database are configured a set of fixtures that will be loaded automatically in the test_xxx db.

Problem

Some migrations need the Postgres hstore extension, in fact i'm getting this error:

django.db.utils.ProgrammingError: type "hstore" does not exist

Question

How can i enable the hstore extension?

In development and other envs it was set up with CREATE EXTENSION IF NOT EXISTS hstore; but here can't be manually set.

Is possible to define a "migration zero" with the hstore creation? Anyway i don't like this approach.

I've found that it should be theorically possible to listen to the pre_migrate signal, and it will be the sweet spot, but before make things more complex i'd like to search for an easier, more direct solution.

Why do some elements exist but not interactable/displayed?

I'm pretty new to testing, trying to gain a better understanding of what exactly is going on. I'm finding some of our test codes are failing when the css selector element has a waitUntilCanInteract or waitUntilDisplayed attached to it even though when I do a chrome inspect the element is showing up in the browser. Changing them to a waitUntilExists gets them to a passing point so I was wondering what exactly is going on to create this situation?

Jmeter :- Running a bundle of samplers sequentially within concurrent threads

I have a single Thread Group with 2 samplers. Lets say Sampler A and Sampler B.

Sampler B is dependent on response of Sampler A.Thus these 2 samplers always have to run sequentially , First - Sample A and then Sample B.

Now my requirement is run this thread group for multiple users concurrently.

When I execute this for one user , it runs fine. However when I run for more than one user , the samplers are not executed sequentially within individual thread group thereby causing Sampler B to fail most of the times.

enter image description here

I need an advice on how can I achieve this.

I tried using Syncronisation Timer , Transaction Controller to bundle the Samplers but it dint work

Need to incorporate Start time and end time against each steps in my Automated script

I want to incorporate start time and end time against each steps in my automated scripts. I am using selenium with java & test NG

strCurrentDate = new SimpleDateFormat(driverProperties.getProperty("logFolderDateFormat")).format(date);
extent = new ExtentReports("./"+driverProperties.getProperty("BatchFileName")+strCurrentDate+".html", false);
extent.loadConfig(new File("./extent-config.xml"));
extent.addSystemInfo("Cockpit Build No.", driverProperties.get("BuildNumber").toString());

NPM - how to publish only if tests pass?

I have tests setup for a package I maintain - create-new-app. When I run npm publish, I want the tests to run first and only if they pass, move on to the publish portion. I thought this is what prepublishOnly was for. My prepublishOnly value looks like this:

prepublishOnly: "npm run test"

That successfully runs the tests prior to publishing, but if the tests fail, it still publishes! How can I get the publish to happen only when tests pass?

Scala EasyMock createNiceMock returns null

Hi I am creating a nice mock of a class whose method returns a spark DF.
I create nice mock because I do not want to get error on the dataframes schema in input.

val nextploraWeboramaDataFrameCombinerMock: DataFrameCombiner = createNiceMock(classOf[DataFrameCombiner])
expect(nextploraWeboramaDataFrameCombinerMock.combineDataFrames(nextFrequency, weboramaManipulated, nextplora))
  .andReturn(nextAugmentedCombined).times(1)
replay(nextploraWeboramaDataFrameCombinerMock)  

However it always returns a null value.
How can this be possible? ù Thanks

JUnit java.lang.NullPointerException [duplicate]

This question already has an answer here:

Im new to software testing, i keep getting java.lang.NullPointerException for some reason and i don't know what it is

This is what i am testing on

public int getNumberOfStudents()
    {
        int validStudents = 0;
        int i = 0;
        boolean done = false;

        do {
            if (students[i] != null && students[i].exists())
                validStudents++;
            else
                done = true;
            i++;
        } while(i < students.length && !done);

        return validStudents;
    } // end of getNumberOfStudents



This is the test case



class Testing {

    RegistrationSystem GNS = new RegistrationSystem();

    @Test
    //@SpiraTestCase(testCaseId=5487)
    public void test() {
        assertEquals("validStudents", GNS.getNumberOfStudents());
    }
    }

Dynamic Snapshot Testing

I have a time differences function that gets a date and calculates it differences with the current time and return time differences like:

4 days ago

Now, I used this function on a web page with some Unit test and Snapshot test. Snapshot testing will fail every day because tomorrow the differences will be 5 days ago

What can I do in this situation?

Codeception: How run e2e test on multiple servers?

I use Codeception to run some Selenium test. I would like to run the same acceptance test suite on multiple server, but I don't knwow how to do it.

This is my codeception.yml:

 # suite config
    suites:
        acceptance:
            actor: AcceptanceTester
            path: .
            modules:
                enabled:
                    - WebDriver:
                        url: http://35.214.136.194
                        host: 215.113.38.27
                        browser: chrome
                    - \Helper\Acceptance

JWS Error during API testing python flask

I am trying to test a function, which basically calls the API by passing a some values, which is then loaded to the schema to be validated and then accepted or rejected based on validation.

The below is my test function.

params = {
   'first': [10,20],
   'second': 400,
   'third ': 'Testing'
}

headers = {
  'Authorization': 'Bearer{}'.format(token),
  'Data-type' : "json"
}

response = self.client.post(url_for('MyView:post', id=current_id.id),
                                                json=params,
                                                headers=headers)

This renders me the error below:

{
  "msg": "Invalid header string: must be a json object"
}

I was able to check the issue and found out its due to the mapping of invalid types. But as headers is still a dictionary, I am not able to comprehend why this error is being rendered.

I have also added the structure of my schema and API below:

class MySchema(marshmallow.Schema):

    id = fields.Integer(required=True)
    second = fields.Integer(fields.Integer(), required=True)
    first = fields.List(fields.String(), required=False)
    third = fields.Str(validate=validate.Length(min=0, max=255), required=False)

    class Meta:
        fields = ('id',
                  'second',
                  'first',
                  'third')

   @validates_schema(pass_original=True)
   def validate_numbers(self, _, data):
       //function code

The below is the structure of my API

 class MyView(V1FlaskView):
   @jwt_requried
   def post(id):
      //code

How to patch a function imported from another module

Not able to patch the function.

I am trying to patch a function from another module in my test function. But I am not able to do that.

response.py

import boto3
lambda = boto3.client('lambda')

def response(event,context):
      s = boto3.client('s')




test_response.py

class lambda_handler(unittest.Testcae):
      @patch('response.boto3')
      test_handler():
       #doing the necessary assertions.

But the above mentioned one gives me the following error

botocore.exceptions.NoRegionError: You must specify a region.


The error is shown for the boto3.client declared outside the response function. Please help me in resolving this issue.

Why does the test fail?

i dont understand why my test is failing can anyone help me ?

        string email = "eldan@dairy.com";
        string password = "010avi";

        LoginPageContext context = new LoginPageContext(_app, false, email, password);
        //Page Navigate
       UserAccountHomePageObject userAccountHomePageObject = new UserAccountHomePageObject(context);
         userAccountHomePageObject.NavigateToPage();

        //Test
        bool status = userAccountHomePageObject.WaitForPage();

        //Assertion
        Assert.IsTrue(status, "Login succeeded");

mardi 27 août 2019

Testsing completableFuture and lambdas

I am working the CompletableFuture class from java 8 and I have to test my code, but I'm struggling, because I don't know how can I test this methods, also I have to test the lambdas that I have used. Now I am using the .join method to block the execution, the problem is that the test don't recognize the lambda variables.

My code looks like this:

        public CompletableFuture<RegistrationInfoDTO> getRegisterInfo(InfoGuestDTO infoInvitedRequest) {
        InvitedLookUpRequest invitedLookUpRequest = generalInfoInvitedToLookUp(infoInvitedRequest);

        return getInfoInvitedService(invitedLookUpRequest)
            .thenCompose(infoRegistration -> findInitialInformation(infoRegistration.getBody(), infoInvitedRequest));
        }

And this is the test that I implemented:

        @Test
        public void findInvitedInfo() {
        HttpHeaders headers = getTestHttpHeaders();
        String mockURL = "url";
        HttpEntity<SeaPassInfoDTO> requestEntity = new HttpEntity<>(seaPassRequestTest, headers);

        given(kidRepository.existsById(anyString())).willReturn(true);
        when(lookUpConfig.getSystem()).thenReturn("KidsClub");
        when(lookUpConfig.getUrl()).thenReturn("anyURL");
        when(restTemplate.exchange(mockURL, HttpMethod.POST, requestEntity, GuestResponse.class))
                .thenReturn(new ResponseEntity<GuestResponse>(guestTest, HttpStatus.OK));

        RegistrationInfoDTO seaPassRegistrationInfo =
                guestGuestLookUpService.getRegistrationInformation(infoGuestDTO).join();

        assertNotNull(seaPassRegistrationInfo);
    }

When I run the test, I get an error because the infoRegistration variable in the

.thenCompose(infoRegistration -> findInitialInformation(infoRegistration.getBody(), infoInvitedRequest));

I wanted to know how can I test this type of methods with lambdas and asynchronous operations. Any advice?. Thanks.

Why got Rspec No route matches error with Rails?

Rails files

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # ...
end

app/controllers/api_application_controller.rb

class ApiApplicationController < ActionController::API
  # ...
end

app/controllers/iot_application_controller.rb

class IotApplicationController < ApiApplicationController
  # ...
end

app/controllers/iot/hardwares_controller.rb

class Iot::HardwaresController < IotApplicationController
  def index
    # ...
  end
end

RSpec file

spec/controllers/iot/hardwares_controller.rb

require 'rails_helper'

RSpec.describe Iot::HardwaresController, type: :controller do
  describe "GET #index" do
    context "with invalid params" do
      it "renders a JSON response with errors" do
        get :index, params: { "test": 1 }
        expect(response).to have_http_status(:bad_request)
      end
    end
  end
end

error

$ rspec .

Iot::HardwaresController
  GET #index
    with invalid params
      renders a JSON response with errors (FAILED - 1)

Failures:

  1) Iot::HardwaresController GET #index with invalid params renders a JSON response with errors
     Failure/Error: get :index, params: {"test": 1}

     ActionController::UrlGenerationError:
       No route matches {:action=>"index", :controller=>"iot/hardwares", :test=>1}
     # ./spec/controllers/iot/hardwares_controller.rb:17:in `block (4 levels) in <top (required)>'

Finished in 0.01547 seconds (files took 6.79 seconds to load)
1 example, 1 failure

How to write route in rspec correctly?

How do I run a unit test for this function that uses the GCS sdk?

I am listing items in my bucket on Google cloud storage. Within the function there is some logic that needs to be tested...trimming directory names and some other things I'd like to make sure that THIS function works. I don't like writing separate functions that are used just for testing. If I were to call the API directly I could easily mock this function with something like httpmock. How do I do it with the sdk?

package gcs

import(
    "cloud.google.com/go/storage"
    "context"
    "google.golang.org/api/iterator"
    "google.golang.org/api/option"
    "strings"
)

// GCS something
type GCS struct{
    client *storage.Client
}

// NewGCSClient something
func NewGCSClient() (*GCS, error){
     c, err := storage.NewClient(context.Background(), option.WithCredentialsFile("..."))
    if err != nil {
        return nil, err
    }

    return &GCS{
        c,
    }, nil
}

// ListItems something
func (g *GCS) ListItems() (entries []string, err error){
    dirPath := "names/"

    q := &storage.Query{
        Prefix: dirPath,
    }

    it := g.client.Bucket("mybucket").Objects(context.Background(), q)
    for {
        attrs, err := it.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            return entries, err
        }

        name := strings.TrimPrefix(attrs.Name, dirPath)
        child := strings.SplitAfter(name, "/")[0]
        entries = append(entries, child)
    }

    return entries, err
}

Backstopjs site loading issue not solved by delay: what is wrong?

When I try to run backstopjs on certain sites (they all must have some dynamic rendering thing in common, though I don't know what), the screenshots generated by backstopjs only include the first piece of content, centered in the screen. Here's the URL to a screenshot: https://user-images.githubusercontent.com/41495147/63806833-1612b680-c8e2-11e9-9932-680864b470b7.png

I've already tried setting the delay to 5 seconds. I've tried waiting until the footer class is available before screenshot. No dice. What is going on? Here's my config file:

  "id": "backstop_default",
  "viewports": [
    {
      "label": "phone",
      "width": 320,
      "height": 480
    },
    {
      "label": "tablet",
      "width": 1024,
      "height": 768
    },
    {
      "label": "desktop",
      "width": 1280,
      "height": 1024
    }
  ],
  "onBeforeScript": "puppet/onBefore.js",
  "onReadyScript": "puppet/onReady.js",
  "scenarios": [
    {
      "label": "VMLYR Home",
      "cookiePath": "backstop_data/engine_scripts/cookies.json",
      "url": "https://www.vmlyr.com",
      "referenceUrl": "",
      "readyEvent": "",
      "readySelector": ".region-footer",
      "delay": 5000,
      "hideSelectors": [],
      "removeSelectors": [],
      "hoverSelector": "",
      "clickSelector": "",
      "postInteractionWait": 0,
      "selectors": [],
      "selectorExpansion": true,
      "expect": 0,
      "misMatchThreshold" : 0.1,
      "requireSameDimensions": true
    }
  ],
  "paths": {
    "bitmaps_reference": "backstop_data/bitmaps_reference",
    "bitmaps_test": "backstop_data/bitmaps_test",
    "engine_scripts": "backstop_data/engine_scripts",
    "html_report": "backstop_data/html_report",
    "ci_report": "backstop_data/ci_report"
  },
  "report": ["browser"],
  "engine": "puppeteer",
  "engineOptions": {
    "args": ["--no-sandbox"]
  },
  "asyncCaptureLimit": 5,
  "asyncCompareLimit": 50,
  "debug": false,
  "debugWindow": false
}```

React and Jest - testing a component using PropTypes.instanceOf

I have a React component using a property defined as an instance of an ES6 class with PropTypes.instanceOf(MyClass).isRequired. When testing using an instance of a mock class, I always get a console error: Warning: Failed prop type.

I tried various techniques based on https://jestjs.io/docs/en/es6-class-mocks and https://reactjs.org/docs/testing-recipes.html , but none of them work: the type never matches what is expected (even when the class name is the same).

How would I test the component using a mock class without removing the type checking ?

Spoofing grpc UnaryHandler for unit testing gRPC in Go

I'm working on improving coverage for my Go gRPC server but I have run into trouble writing a test for the server's interceptor function because I'm unable to meaningfully satisfy the UnaryHandler type.

I have a function Interceptor with the following signature:

Interceptor func(
  ctx context.Context,
  req interface{},
  info *grpc.UnaryServerInfo,
  handler grpc.UnaryHandler, // <- my issue comes from here
) (interface{}, error)

I assumed that any gRPC method would satisfy the signature of UnaryHandler:

type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error)

So I tried passing in a method with this signature:

GetToken(ctx context.Context, req *AuthData) (*Token, error)

I imagined this would work, since this is what the Interceptor is actually doing (forwarding that RPC), but for some reason Go complains:

cannot use authService.GetToken (type func(context.Context, *AuthData) (*Token, error)) as type grpc.UnaryHandler in argument to Interceptor

I went ahead and wrote a dummy function that correctly satisfies:

func genericHandler(ctx context.Context, req interface{}) (interface{}, error) {
    return req, nil
}

which is fine since I don't particularly need to run any specific method when testing the interceptor. However I am curious as to why the actual method doesn't satisfy the constraints because (according to my understanding) it is being passed to the Interceptor function under hood whenever I call that RPC in the wild.

The most likely explanation is that the grpc UnaryHandler doesn't do what I'm thinking it does, but then what does it do?

Is it possible to run a java program inside a Junit test?

Context:

My company has a tool written in Java, that is run on the command line interface. To run this tool on the command line:

gradle clean gradle build cd multiple times unpack rar files ./run_tool.sh parameter1 parameter2 parameter3

My company also has an automation test codebase that consists of JUnit tests. I have to write an automated test that runs the tool.

I know it is possible to run a script inside a Java program. However, the examples I saw did not show how to run a script with parameters. Furthermore, the examples I saw were simple scripts, not full Java programs.

I do not know if what I am trying to do is even possible. Can anyone please suggest potential approaches?

Command errored out with exit status one

i am installing qark in my pc(Windows 7) for testing purpose i have installed python 3.7.2 and pip 19.2.3 for next step i have to install the requirement.txt file while installing an error occurred(Command errored out with exit status 1:) full error i will is give below.

i tried installing it again but error was same i don't know what should i do help me. thank you

    ERROR: Command errored out with exit status 1:
     command: 'c:\users\hp\appdata\local\programs\python\python37\python.exe' -c
 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\HP\\AppData\\L
ocal\\Temp\\pip-install-6tjj0pbq\\cffi\\setup.py'"'"'; __file__='"'"'C:\\Users\\
HP\\AppData\\Local\\Temp\\pip-install-6tjj0pbq\\cffi\\setup.py'"'"';f=getattr(to
kenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"
'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --
egg-base pip-egg-info
         cwd: C:\Users\HP\AppData\Local\Temp\pip-install-6tjj0pbq\cffi\
    Complete output (27 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\HP\AppData\Local\Temp\pip-install-6tjj0pbq\cffi\setup.py",
line 120, in <module>
        if sys.platform == 'win32' and uses_msvc():
      File "C:\Users\HP\AppData\Local\Temp\pip-install-6tjj0pbq\cffi\setup.py",
line 98, in uses_msvc
        return config.try_compile('#ifndef _MSC_VER\n#error "not MSVC"\n#endif')

      File "c:\users\hp\appdata\local\programs\python\python37\lib\distutils\com
mand\config.py", line 227, in try_compile
        self._compile(body, headers, include_dirs, lang)
      File "c:\users\hp\appdata\local\programs\python\python37\lib\distutils\com
mand\config.py", line 133, in _compile
        self.compiler.compile([src], include_dirs=include_dirs)
      File "c:\users\hp\appdata\local\programs\python\python37\lib\distutils\_ms
vccompiler.py", line 345, in compile
        self.initialize()
      File "c:\users\hp\appdata\local\programs\python\python37\lib\distutils\_ms
vccompiler.py", line 238, in initialize
        vc_env = _get_vc_env(plat_spec)
      File "c:\users\hp\appdata\local\programs\python\python37\lib\site-packages
\setuptools\msvc.py", line 185, in msvc14_get_vc_env
        return EnvironmentInfo(plat_spec, vc_min_ver=14.0).return_env()
      File "c:\users\hp\appdata\local\programs\python\python37\lib\site-packages
\setuptools\msvc.py", line 1228, in return_env
        self.OSIncludes,
      File "c:\users\hp\appdata\local\programs\python\python37\lib\site-packages
\setuptools\msvc.py", line 963, in OSIncludes
        sdkver = self._sdk_subdir
      File "c:\users\hp\appdata\local\programs\python\python37\lib\site-packages
\setuptools\msvc.py", line 1057, in _sdk_subdir
        ucrtver = self.si.WindowsSdkLastVersion
      File "c:\users\hp\appdata\local\programs\python\python37\lib\site-packages
\setuptools\msvc.py", line 604, in WindowsSdkLastVersion
        self.WindowsSdkDir, 'lib'))
      File "c:\users\hp\appdata\local\programs\python\python37\lib\site-packages
\setuptools\msvc.py", line 809, in _use_last_dir_name
        for dir_name in reversed(os.listdir(path))
    FileNotFoundError: [WinError 3] The system cannot find the path specified: '
C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\PlatformSDK\\lib'
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check th
e logs for full command output.