dimanche 31 janvier 2021

I cannot find uiautomationviewer file

I downloaded command line tools from android studio and unzip. However, I cannot find uiautomationviewer file. I looked all file in the folder but I cannot find it. Where can I find the file?

How to get cypress to return children length of 0 when there isnt any children

So I am writing a test that will add a card to a container(payment-card-container) and I want to confirm an element was added later by seeing if the children have increased by 1. But I am having issues when we try to count the children length when there isnt any. I am currently using the below:

cy.get('[data-test-id="payment-card-container"]')
    .children()
    .its('length')
    .then(length => {
        const childrenLength = length;
    })

But Cypress seems to get an error because it cant find the children (Error below).

Timed out retrying: Expected to find element: ``, but never found it.

Is there a way this can work when there isnt any children and it returns the value of 0?

Selenium webdriver automation test gives Error: A device attached to the system is not functioning. (0x1F)

My selenium test cases are written in JavaScript for testing my react application but it gives unusual error

  1. Bluetooth: bluetooth_adapter_winrt.cc:713 GetBluetoothAdapterStaticsActivationFactory failed: Class not registered (0x80040154).

  2. :ERROR:device_event_log_impl.cc(211)] [09:24:47.641] USB: usb_device_handle_win.cc:1020 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F).

  3. Also it is not able to click few buttons.

Docker crashes when renderer process eats up too much memory cypress?

Build Error! Build Error: We did not receive any logs from your build for a while so it was stopped

We detected that the Chromium Renderer process just crashed. This is the equivalent to seeing the 'sad face' when Chrome dies. This can happen for a number of different reasons:

  • You wrote an endless loop and you must fix your own code
  • There is a memory leak in Cypress (unlikely but possible)
  • You are running Docker (there is an easy fix for this: see link below)
  • You are running lots of tests on a memory intense application
  • You are running in a memory starved VM environment
  • There are problems with your GPU / GPU drivers
  • There are browser bugs in Chromium You can learn more including how to fix Docker here: https://on.cypress.io/renderer-process-crashed

Angular and Jest: Mocking service is ignored

I have:

Service 1

@Injectable({ providedIn: 'root' })
export class OrganisationApiService {
  constructor(
     private httpClient: HttpClient,
     private env: EnvironmentService
  ) {}

  public getOrganisations(): Observable<Organisations[]> {
     return this.httpClient.get<Organisations[]>(this.env.environment.organisationApi);
  }
}

This service has EnvironmentService which just acts as a way to allow for injection of a a ts file which has an exported object, this object needs to be changed in certain circumstances (testing being one of them).

The test for this has the following setup block:

beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule]
    });
    TestBed.overrideProvider(EnvironmentService, { useValue: {} });
    organisationApiService = TestBed.inject(OrganisationApiService);
    httpMock = TestBed.inject(HttpTestingController);
});

Unfortunately what seems to be happening is instead of overriding the EnvironmentService it uses the original service, the original service has other dependencies and it obviously throws an error stating as much.

I originally used the providers section in the configureTestingModule definition but that did not work which is why I have tried to use the overrideProvider, at this point I am out of ideas.

Anyone got a solution?

How to only perform a subset of gradle tasks during test. Spring Boot

building a Spring Boot API with a javascript frontend.

I have a task that builds my javascript so that it can deploy alongside the API, but it takes a minute or two and I don't want to do it under test.

Wondering if there are any best practices for how to do this before I start rolling my own or digging into the nuts and bolts of gradle and the tasks that depend on gradle test

Spring Boot mock/stub multipe endpoints for component test

I want to create a component test, for a rest endpoint that contact multiple other rest endpoints. The addresses for the endpoints are defined in application.properties. Using WebClient to contact the different endpoints.

req --> service --> remoteService A
                --> remoteService B
                --> remoteService C

How do I stub remoteService A,B and C in a Spring Boot test? I would like to stub the url to the remote services directly instead of overriding the beans for them.

Django testing (TestCase) with multiple database is failing

I use 2 databases on my django app - the first is MySQL and the second is Mongo (using the djongo engine).

I started writing some tests using the TestCase and i want to use sqlite3 engine.

My DBs configuration: (You can see that i have assigned TEST DBs on sqlite]

#settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DEFAULT_NAME,
        'USER': DEFAULT_USER,
        'PASSWORD': DEFAULT_PASSWORD,
        'HOST': 'my-host-here',
        'PORT': '3306',
        'TEST': {
            'NAME': 'test_dev'
        }
    },

    'mongoDB': {
    'ENGINE': 'djongo',
    'CLIENT': {
        'host': 'mongodb+srv://{}:{}@{}/?retryWrites=true&w=majority'.format(
            username,
            password,
            host),
        'username': username,
        'password': password,
        'name': name,
        'authSource': authSoruce,
        'ssl':ssl,
        'authMechanism': 'SCRAM-SHA-1',
        }
    }
}

# If django runs unittests - run on a local sqlite DB
if 'test' in sys.argv:
    DATABASES['default'] = {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'mydatabase',
        'SUPPORTS_TRANSACTIONS': True
    }

    DATABASES['mongoDB'] = {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'mydatabase2',
        'SUPPORTS_TRANSACTIONS': True
    }

When i run the tests, I get failures when Django is trying to create the mongoDB TEST database. error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: release_notes_releasenotesformmodel (release_notes_releasenotesformmodel is the only model i have in the mongoDB)

test script:

    databases = '__all__'

    def SetUp(self):
        self.client = Client()
        self.dummy_test = EdisonAbTestsListModel.objects.create(
            test_id=DUMMY_TEST_ID_1
        )

    def run_test(self):
        ## here is my test logic...

As you can see i tried to use the databases = '__all__' in the TestCase config, but it won't help

EDIT: this i the release_notes_releasenotesformmodel model:

    class Meta:
        db_table = 'release_notes'

    _DATABASE = "edison_mongo"

    # Automated fields
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True)
    # Model Fields
    '''
        test_id is actually the primary key in to EdisonAbTestsListModel
        Notice: for 'full_rollout' RNs, test_id is populated but has no meaning. 
                for 'full_rollout' RNs The minimum id should match FULL_ROLLOUT_RN_MINIMUM_ID from views.py 
    '''
    test_id = models.IntegerField(primary_key=True)

    release_note_title = models.CharField(max_length=300, blank=True, null=False)
    user_group = models.CharField(max_length=200, blank=True, null=True)

    tl_dr = models.CharField(max_length=10000, blank=True, null=True)
    owner = models.CharField(max_length=200, blank=True, null=True)
    dev_owner = models.CharField(max_length=200, blank=True, null=True)
    data_owner = models.CharField(max_length=200, blank=True, null=True)
    ds_owner = models.CharField(max_length=200, blank=True, null=True)

How to test Vue in CDN mode?

I set up my vue & vuex project using cdn but not npm like this:

index.php:

<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.1/vue.js"></script>

app.js:

const app = new Vue({
  el: '#app',
  components: {component1},
  template: `<component1 />`
})

components in js files:

export default{
  name: 'component1',
  template: `<p>Hello World</p>`
}

So that all my components are js files and I don't have a package.json. Now I'm trying to test my components using jest and @vue/test-utils, is there a way to setup test framework without using npm?

Toggling assert testing

I have two source files: one I want to test via asserts, the second containing the asserts.

My problem is that I do not want the testing to be run each time the program itself is run, so is there a way to toggle assert testing on or off depending on a makefile argument?

Or will I have to create another source file, containing both the code I want to test and the assert testing itself?

How to mock an object that is declared and created in the local scope of a method?

So I am unit testing a class(it extends from SourceTask in org.apache.kafka.connect.source.SourceTask) and this class needs to Mock some objects than interact with it to do unit testing, and I am doing so with EasyMock. The problem is that inside this class there is a method which makes an HTTP request to an URL, but the HttpUriRequest object is created and declared in the scope of the method(locally). Can I still mock this object although it is declared, created and used in the local scope of a method? If not, two possible solutions come to my mind:

  1. Create a local server which I can tweak to develop several test cases(now instead of mocking the HttpUriRequest I would be creating my own server so I can customize it to act as necessary in each test). But I do not know if this is correct for a unit test.
  2. Develop a Class that represents the connections to the server, I mean to extract all of the logic of the HTTP connections to another class that would be instantiated as an attribute in the class I am trying to test. This way I can now mock it easily. So may be my problem comes from a design mistake of my classes :/.

How this test can be fixed?

I am beginner to java and testing. I am getting error with the test @shouldAddOrderToTheList() : Expected :5 Actual :1. Could you please point to me what is wrong and how it can be fixed?

class ShopTestSuite {


    Shop shop = new Shop();

    Order order1 = new Order(12.30, LocalDate.of(2020, 12, 12), "marta123");
    Order order2 = new Order(67.89, LocalDate.of(2019, 1, 12), "Tomek_K");
    Order order3 = new Order(123.90, LocalDate.of(2020, 2, 2), "Sylwia");
    Order order4 = new Order(22.90, LocalDate.of(2020, 6, 20), "Sylwia");


    @Test
    public void shouldAddOrderToTheList() {
        // When
        shop.addOrder(new Order(23, LocalDate.now(), "zz"));
        // Then
        assertEquals(5, shop.getAllOrders().size());
    }

CLASS SHOP

public class Shop {

    private Set<Order> orders = new HashSet<>();

   public void addOrder (Order order) {
       this.orders.add(order);

   }

  public Set<Order> getAllOrders(){
        return this.orders;
    }
  
  }

AFL taking input from Stdin

I am trying to Fuzz a binary file that takes input from the user(Stdin). When I try Afl-fuzz and then my binary something like

afl-fuzz a.out

It asks for the required parameters that are specifying the input and output directories.

afl-fuzz -i input_dir -o output_dir a.out 

It gives the error Looks like there are no valid test cases in the input directory. If I provide a sample test case and try again it starts fuzzing but doesn't ask for input from the user. I am a total noob in this field so any kind of help would be appreciated.

Cognitive Walkthrough of Stackoverflow

For my studies I have to do a cognitive walkthrough of stackoverflow. This includes testing the posting feature and finding possible problems there.

You do not have to answer to this question. I will delete the question in some time, after I finished my evaluation.

However, if you know some problems with stackoverflow regarding a cognitive walkthrough, feel free to let me know. Of course you don't have to do my assignment for me and I will hopefully finish them on my own.

testing the code feature...

I hope you have a good day.

Best regards, a working student

Is it okay to copy a class method and test its behavior by mocking the class and dependencies in unit tests?

Or I need mock all other methods and dependencies(huge amount) in the class by using @patch, and test through a class call(call method cls.execute() in my service)?

Simple example what I meant:

import unittest
from unittest import mock
from .my_services import MyService

class MyServiceTestCase(unittest.TestCase):

    def test_set_name(self):
        mocked_service = mock.Mock()
        mocked_service._names = ["Arnold", "Ken", "Alex"]
        mocked_service.exact_name = ""

        set_last_name = MyService.set_last_name
        set_last_name(mocked_service)

        self.assertEqual(mocked_service.exact_name, "Alex")

Imagine that to get the ._names you'll need to call five other methods by making calls to the database and api.

I'm new to testing. So copying the method and testing it separately, checking the desired changes in the mocked class seems like a good idea to me. But is it really so?

rails testing with devise-defined current_user

A rails controller test is invoking an action where its form calls

  f.hidden_field :user_id, value: current_user.id

the controllerTest attempts to define the current_user in the action call

test "should get edit" do
  @shopusers.each do |user|
    current_user = user
    sign_in user

but fails specifically on that line:

ActionView::Template::Error: undefined method `user_id' for nil:NilClass
    app/views/transactions/_form.html.erb:14

How should one go about defining the current_user for the purposes of a test

samedi 30 janvier 2021

Adding annotation to test methods

I'm not sure 'annotations' is the current term, I'll try to explain by example:

    [MyAnnotation]
    [TestMethod]
    public void Test123()
    {
        ...
    }

I want to define 'MyAnnotation' to affect the method in some way. Is that possible? Couldn't find useful information about it. Thanks.

Unable to create an emulator using android studio

I installed android studio on MacBook Pro but when I try to create a virtual device it shows me an error saying that cpu does not support vt-x.

Tests don't pass using react-testing-library when adding firebase persistance, but when testing manually, everything works

I am testing my SingIn component in my React app. All tests passed until I added firebase.auth().setPersistance() to my submit handler. I use jest with react-testing-library for tests.

part of test that fails:

typeLoginCredentials(email, 'badpassword');
act(() => {
  userEvent.click(screen.getByText(/Login/));
});
expect(await screen.findByText(/Wrong password/)).toBeInTheDocument();

and part of my submit handler:

...
try {
  let persistence = rememberAuth ? firebase.auth.Auth.Persistence.LOCAL : 
                                   firebase.auth.Auth.Persistence.SESSION;
  await fireApp
    .auth()
    .setPersistence(persistence);
  await fireApp
     .auth()
     .signInWithEmailAndPassword(email, password);
...

When i test this manually in my browser, everything works fine. But tests pass only when I remove persistence part:

await fireApp.auth().setPersistence(persistence);

I even tried to change findBy timeout, but it didn't help.

Async callback not invoked within the 5000ms timeout specified by jest.setTimeout

New to the testing world, I've been struggling to understand why I'm getting the following error while testing the following endpoint with Jest on this very simple API. Would be very grateful if you could give me a hint on the reason why I'm getting the error in detailed below, and how to fix it. Been looking around answers on this particular issue and I'm pretty sure it is related to some promisy thing but don't know how to implement it.

Thank you 🙏

// server.js

const express = require('express');
const app = express();

const carts = new Map();

app.get('/carts/:username/items', (req, res) => {
   const userCart = carts.get(req.params.username);
   userCart ? res.status(200).json(userCart) : res.status(404);
});

module.exports = { app: app.listen(3000) };
// server.test.js

const { app } = require('./server');
const fetch = require('isomorphic-fetch');

const apiRoot = 'http://localhost:3000';

const getItems = (username) => {
    return fetch(`${apiRoot}/carts/${username}/items`, {
        method: 'GET',
    });
};

afterAll(() => app.close());

test('Adds an item to a cart',  async() => {
   const getItemsResponse = await getItems('test_user');
   expect(getItemsResponse.status).toEqual(404);
});
Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.
Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error: 
    at new Spec (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
    at new Spec (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-jasmine2/build/setup_jest_globals.js:78:9)
    at new JBPatchedSpec (/Applications/WebStorm.app/Contents/plugins/JavaScriptLanguage/helpers/jest-intellij/lib/jest-intellij-jasmine-reporter.js:94:7)
    at specFactory (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-jasmine2/build/jasmine/Env.js:523:24)
    at Env.it (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-jasmine2/build/jasmine/Env.js:592:24)
    at Env.it (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:134:23)
    at it (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-jasmine2/build/jasmine/jasmineLight.js:100:21)
    at Object.<anonymous> (/Users/alexandrecoin/Desktop/testing_javascript/server.test.js:14:1)
    at Runtime._execModule (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-runtime/build/index.js:1299:24)
    at Runtime._loadModule (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-runtime/build/index.js:898:12)
    at Runtime.requireModule (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-runtime/build/index.js:746:10)
    at jasmine2 (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-jasmine2/build/index.js:230:13)
    at runTestInternal (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-runner/build/runTest.js:380:22)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at runTest (/Users/alexandrecoin/Desktop/testing_javascript/node_modules/jest-runner/build/runTest.js:472:34)

how to prepare a test case for Gmail file attachment with their file type and size?

I was wondering if anyone could help me out with this question. I try to write some of it but it is not enough. it's urgent please help me!

How to Automate Swagger APIs using Selenium WebDriver

I am trying to Automate the Swagger's APIs using the Selenium Webdriver tool.

Can anyone suggest, How can I start and How can automate those APIs?

Testing repository with firebase and coroutines keeps hanging when calling .await()

I am having an issue with my repository tests. This is the first time I've really used Firebase, and they come with coroutines out of the box now, so I thought I'd use them

But when I am setting up a test, it is hanging forever when calling the coroutines await()

Here are the contents of my test class, followed by the method I am testing.

    @JvmField
    @Rule
    val rule = InstantTaskExecutorRule()

    @get:Rule
    val testCoroutineRule = TestCoroutineRule()

    private lateinit var subject: UserDataRepository

    @MockK
    private lateinit var firestoreRef: FirebaseFirestore
    @MockK
    private lateinit var firebaseAuth: FirebaseAuth
    @MockK
    private lateinit var firebaseStorage: FirebaseStorage
    @MockK
    private lateinit var userDao: UserDao
    @MockK
    private lateinit var context: Context
    @MockK
    private lateinit var authResult: AuthResult

    private val USERS = "Users"

    private val user = UserData("Jo Bloggs")
    private val email = "itsyaboijo@gmizzle.com"
    private val password = "iLovefluffycats863$"
    private val username = user.name
    private val uid = "d98dy1x/;10v84i1[,'1"
    private val data = hashMapOf("name" to user.name)

    @Before
    fun setup() {
        MockKAnnotations.init(this)
        every { context.getExternalFilesDir(null)?.absolutePath } returns "testing/path/child"
        subject = UserDataRepository(
            context,
            firestoreRef,
            firebaseAuth,
            firebaseStorage,
            userDao
        )
    }
    
    @Test
    fun `when createUser called successfully then returns AuthResult`() {
        testCoroutineRule.runBlockingTest {
            //GIVEN
            coEvery { userDao.addUser(user) } returns 1
            coEvery { firebaseAuth.createUserWithEmailAndPassword(email, password).await() } returns authResult
            coEvery { firestoreRef.collection(USERS).document(uid).set(data).await() }

            //WHEN
            val actualAuthResult = subject.createUser(email, password, username)

            //THEN
            Assert.assertEquals(authResult, actualAuthResult)
        }
    }

Tested Method:

    suspend fun createUser(email: String, password: String, username: String): AuthResult {
        userDao.addUser(UserData(username))
        val data = hashMapOf(
            "name" to username
        )
        val authResult = firebaseAuth.createUserWithEmailAndPassword(email, password).await()
        firestoreRef.collection("Users")
            .document(firebaseAuth.currentUser!!.uid)
            .set(data).await()
        return authResult
    }

vendredi 29 janvier 2021

Use test helper function in controller test

I am getting the following error when I try to use a test helper function:

undefined function myfunction/0

the setup is as follows:

defmodule MyAppWeb.DashboardControllerTest do
  use MyAppWebWeb.ConnCase

  import TestHelpers

  describe "index" do
    setup [:myfunction] #<- This works perfectly
  
    test "some test", %{conn: conn} do
      conn = get(conn, "/")

      var = myfunction #<- This does not work
    end
  end
end

The test helper looks like this:

# File is located in "support/test_helpers.ex"

defmodule TestHelpers do

  def myfunction do
   #magic!
  end
end

It would be great if someone could elaborate! Thanks in advance!

Issues with testing flash game

I've got a task where i have to test a game made in flash. It's Icy Tower kind of game where water is constantly chasing you while you try to get as high as possible. I wonder if there is a posibility to turn off this feature. Is there any posibility to change code of this game? Got only .exe file.

How to test a function passed as props to child in React?

I need some advice on how to write tests for React component. I have 2 approaches in my mind, feel free to suggest more.

I have a component App which renders a ComplexSearchBox. I pass this ComplexSearchBox a prop onSearch, the value of this prop is a function. This function is invoked by ComplexSearchBox at various user interactions like when the user hits enter on the input box or clicks the search button.

const App = () => {
    return <ComplexSearchBox onSearch={query => console.log(query)}/>;
};

I want to write tests for App component. I'm using Enzyme to write tests. I'm following some principles of React Testing Library. I'm mounting the component. So this will render all children as well. I don't want to render ComplexSearchBox so I'll mock it.

This is where my problem is. I have 2 approaches in my mind.

  1. I can get the props of ComplexSearchBox and invoke the method directly with the required parameters.
jest.mock('Path To ComplexSearchBox', function ComplexSearchBox() {
    return null;
});

describe('App', () => {
    describe('when search button is clicked', () => {
        it('should log to console by invoking prop method', () => {
            const wrapper = mount(<App/>);
            wrapper.find('ComplexSearchBox').props().onSearch('My random test query');
            //expect something
        });
    });
});
  1. I can mock the ComplexSearchBox and return a simplified version of it. Now I can type the query in an input box and then click a button to submit.
jest.mock('Path To ComplexSearchBox', function ComplexSearchBox({onSearch}) {
    const [query, setQuery] = useState('Sample Search Query');
    return <div>
        <input value={query} onChange={setQuery}/>
        <button onClick={() => onSearch(query)}/>
    </div>;
});

describe('App', () => {
    describe('when search button is clicked', () => {
        it('should log to console by clicking', () => {
            const wrapper = mount(<App/>);
            wrapper.find('input').simulate('change', {target: {value: 'My random test query'}});
            wrapper.find('button').simulate('click');
            //expect something
        });
    });
});

I see value in the second approach. However, I'm not sure if it is worth the effort of creating a simplified version every time I have to interact with a child component.

The benefit of the second approach is that

  1. It decouples the code from tests. My tests don't have to know which method to invoke with what parameter when the user wants to execute a search. Mock knows which method to invoke but that is at one place and not spread across all the tests.
  2. I find tests to be more readable and behaviour oriented when written this way.
  3. This mock can be extracted out and used at multiple places. Making writing tests easier.
  4. Any method sequencing can be abstracted in the mock component. Like if I modify the ComplexSearchBox as below.
const App = () => {
    return <ComplexSearchBox preProcess={()=>{}} onSearch={query => console.log(query)} postProcess={()=>{}}/>;
};

jest.mock('Path To ComplexSearchBox', function ComplexSearchBox({preProcess, onSearch, postProcess}) {
    const [query, setQuery] = useState('Sample Search Query');
    const search = (query) => {
        const preProcessedQuery = preProcess(query);
        const searchedQuery = onSearch(preProcessedQuery);
        postProcess(searchedQuery);
    };
    return <div>
        <input value={query} onChange={setQuery}/>
        <button onClick={() => search(query)}/>
    </div>;
});

Though I'm not very sure if the last benefit is really a benefit. As now my mock is aware of the lifecycle of ComplexSearchBox. But on the other hand, this mock will be written only once and will save me from calling those 3 methods one after the other in a lot of tests. I could also argue that a component test written with approach one should not really care about the method sequencing as that is ComplexSearchBox responsibility. Those 3 methods do have a tight coupling as one's output is next one's input. And now I'm borderline integration testing these 2 components.

I could also have 3 buttons which have onClick to run those 3 methods and now I can test them individually.

I'm not really sure which approach is better. I'm leaning a bit towards approach 2 because it makes my tests less dependent on implementation.

I'd appreciate any advice on this and if you have another way to test this scenario then please share.

Android mockito argument needs to be mock exception

I am trying to test my function with JUnit + Mockito. My function is using Amadeus API to fetch flight offers with given specification.

amadeus.shopping.flightOffers.get(...).handleResponse(
    onSuccess = { response ->
        when (response.isEmpty()) {
            true -> requestStatus.value = Status.EMPTY
            else -> requestStatus.value = Status.SUCCESS
        }
        view?.onSearchFlightSuccess(response)
    },
    onError = { exception, errors ->
        requestStatus.value = Status.FAILED
        view?.onSearchFlightError(exception)
    }
 )

handleResponse function is my extension over Amadeus's ApiResult

fun <T> ApiResult<T>.handleResponse(onSuccess: (T) -> Unit, onError: (Exception?, List<ApiResult.Error.Issue>) -> Unit) {
    when (this) {
        is ApiResult.Success -> onSuccess(data)
        is ApiResult.Error -> onError(exception, errors)
    }
}

So I am not very experienced in testing, but I found many articles on the internet how to do it, but somehow it doesn't work.

@Test
@ExperimentalCoroutinesApi
fun onSearchFlightsButtonClick() = runBlockingTest {
    given(amadeus.shopping).willReturn(mock(Shopping::class.java))
    given(amadeus.shopping.flightOffers).willReturn(mock(FlightOffers::class.java))

    given(amadeus.shopping.flightOffers.get(...))
    .willReturn(mock(ApiResult::class.java) as ApiResult<List<FlightOfferSearch>>)


    `when`(mock(ApiResult::class.java).handleResponse(mock(CallbackSuccess::class.java)::invoke,
        mock(CallbackError::class.java)::invoke)
    ).then { answer -> (answer.arguments[0] as (List<FlightOfferSearch>) -> Unit).invoke(emptyList()) }


    presenter.onSearchFlightsButtonClick()

    Mockito.verify(view).onSearchFlightSuccess(emptyList())
}


interface CallbackSuccess {
    operator fun invoke(value: Any?)
}

interface CallbackError {
    operator fun invoke(exception: Exception?, issues: List<ApiResult.Error.Issue>)
}

I pass interfaces to my extension function because Mockito.any() didn't work and threw up exception: any() can not be null. Can someone point out what is wrong here?

Above code throws:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

Hilt BindValue and ActivityRetainedComponent not working in android instrumented tests

Hi everyone I am trying to use hilt in my instrumented test and even though the app is working fine the tests seem to have an issue with the dependencies Here is a link to my repo, and here is the test here is my test


@UninstallModules(WaterTrackingModule::class)
@HiltAndroidTest
class WaterTrackerTest {

    @get:Rule val hiltRule = HiltAndroidRule(this)


    @BindValue
    @JvmField val preferencesHelper = mock<PreferencesHelper>()

    @Before fun init() = hiltRule.inject()

    @Test
    fun waterCountDisplays() {
        val waterIntake = 5
        whenever(preferencesHelper.waterIntake())
            .doReturn(waterIntake)
        ActivityScenario.launch(WaterTrackerActivity::class.java)
        onView(withId(R.id.waterCountText))
            .check(matches(withText(waterIntake.toString())))
    }
}

and here is the WaterTrackingModule

@InstallIn(ActivityRetainedComponent::class)
@Module
class WaterTrackingModule {

    @ActivityRetainedScoped
    @Provides
    fun providesPreferencesHelper(
        @ApplicationContext context: Context
    ) = PreferencesHelper(context)
}

The test fails with this message

  public abstract static class SingletonC implements WaterTrackerApplication_GeneratedInjector,
                         ^
      com.abdelrahman.watertracker.PreferencesHelper is injected at
          com.abdelrahman.watertracker.WaterTrackingViewModel(preferencesHelper, …)
      com.abdelrahman.watertracker.WaterTrackingViewModel is injected at
          com.abdelrahman.watertracker.WaterTrackingViewModel_HiltModules.BindsModule.binds(arg0)
      @dagger.hilt.android.internal.lifecycle.HiltViewModelMap java.util.Map<java.lang.String,javax.inject.Provider<androidx.lifecycle.ViewModel>> is requested at
          dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.ViewModelFactoriesEntryPoint.getHiltViewModelMap() [com.abdelrahman.watertracker.WaterTrackerTest_HiltComponents.SingletonC → com.abdelrahman.watertracker.WaterTrackerTest_HiltComponents.ActivityRetainedC → com.abdelrahman.watertracker.WaterTrackerTest_HiltComponents.ViewModelC]
  It is also requested at:
      com.abdelrahman.watertracker.WaterCountTextView.preferencesHelper
  The following other entry points also depend on it:
      com.ab

TestCafe: console.log() the value of a selector

I try to select the text value SR-12948 of the span below with a TestCafe selector and then assign it to a const. So I can add it as a string to the withAttribute method. That doesn't really work. So I want to check what the value of my const srCaseIDString is. Is it possible to do that with a console log? So it logs the value of that const in the same terminal as my test results and errors appear?

This is my test:

<span data-template="" data-test-id="2014100715101007275150" class="supporting_text_il" style="">SR-12948</span>

import { Selector, t } from "testcafe";
import XPathSelector from "../utils/xpath-selector";

const button= Selector("#button");  

test("First Test", async (t) => {
     await t
        .click(button);

        const srCaseID = await  XPathSelector("//span[@data-test-id='2014100715101007275150']").innerText;
        const srCaseIDString = await srCaseID.innertext;

        console.log(srCaseIDString )

        const iframeCase = await Selector('iframe').withAttribute('title', srCaseIDString);
       
        await t
        .switchToIframe(iframeCase);
     
});

Thanks!

What is the best unit testing design for form tests?

The problem relates to the tests design. I'm attaching a pseudo code. let's assume that:

  • the form consists not of 3, but 14 (or more) fields
  • and each field has more business logic that needs to be tested (say 150 tests for the form)
  • the proportions are that 75% of the tests will be the same for each field, 25% of the tests will be specific to each field on

Suppose this is an extended form which:

  • disables fields when form is submitting
  • shows validation error for each field. Some validators are the same (eg. "required"), some are specific for the particular fields (eg. email)
  • sends to analytics event (eg google analytics) field that user has started as the first one
  • also, field where a user commits an error
<form>
  <input name="firstName" disabled={isFormSubmitting} />
  <input name="lastName" disabled={isFormSubmitting} />
  <input name="email" disabled={isFormSubmitting} />
</form>

Here the pseudocode for tests:

// APPROACH 1 - one field, single tests, single assertion

describe('first name field', () => {
  test('should disable field when form is submitting', () => {});
  test('should display "required" error when form has been submitted without value', () => {});
  test('should send analytics event when user has started filling this field as the first one ', () => {});
  test('should send analytics event when user has committed an error', () => {});
});
describe('last name field', () => {
  /* the same tests + the ones specifir for the last name field */
});
describe('email field', () => {
  /* the same tests + the ones specifir for the email field */
});

// APPROACH 2 - tests for all fields at once if business logic is the same for all fields

test('should disable all fields when form is submitting', () => {});
test('should display "required" error for all fields when form has been submitted without values', () => {});
test('should send analytics event with field name when a user has started filling any field', () => {});
test('should send analytics event with field name when a user has committed an error for any field', () => {});

// but where tests which busines logic is specific for particular fields?

// APPROACH 3 - group by business logic. "one business logic", single tests, single assertion

describe('disabling fields', () => {
  test('should disable first name field when form is submitting', () => {});
  test('should disable last name field when form is submitting', () => {});
  test('should disable email field when form is submitting', () => {});
});
describe('showing required error', () => {
  test('should display "required" error for first name field when form has been submitted without value', () => {});
  test('should display "required" error for last name field when form has been submitted without value', () => {});
  test('should display "required" error for email field when form has been submitted without value', () => {});
});
describe('sending "a user started filling a field" analytics event', () => {});
describe('sending "a user committed an error" analytics event', () => {});

My question is which approach is better:

  • approach 1: is it better to group the tests into fields and test each field separately?
  • approach 2: is it better to group the tests into business logic and test all fields that behave the same in one test
  • approach 3: is it better to group the tests into business logic and each field should have its own test

How to run unit test which testing the script with argparse attributes?

I have got a simple program my_code.py with argparse and test_code.py with the test code. Please help me with how I should run correctly the test_code.py. When I try basic commands I get an error like below:

test: python -m unittest test_code.py

AttributeError: 'module' object has no attribute 'py'

test case: python -m unittest test_code.Test_Code

python -m unittest: error: too few arguments

test method: python -m unittest test_code.Test_Code.test_double_name

python.exe -m unittest: error: the following arguments are required: name


    # my_code.py
    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("name")
    parser.add_argument('-d', '--double', action="store_true")
    
    def double_name(new_name):
      if args.double:
        return new_name + new_name
      else:
        return new_name
    
    if __name__ == "__main__":
        args = parser.parse_args()
        print(double_name(args.name))

    # test_code.py
    import unittest
    import my_code
    
    class Test_Code(unittest.TestCase):
    
      def test_double_name(self):
        my_code.args = my_code.parser.parse_args([])
        self.assertEqual(my_code.double_name('test-name'), 'test-name')
    
        my_code.args = my_code.parser.parse_args(["test-name", "-d"])
        self.assertEqual(my_code.double_name('test-name'), 'test-nametest-name')
    
    if __name__ == "__main__":
      unittest.main()

jeudi 28 janvier 2021

Test failed of a Component in react using typescript

When ever I run the test it fails. I don't know what mistake I am making.

How can I test those if statements and the child component. I am using jest and enzyme for react tests.

This is my test file:

import React from "react";
import { shallow } from "enzyme";
import LaunchContainer from "./index";
import Launch from "./Launch";

describe("render LaunchContainer component", () => {

    let container: any;
    beforeEach(() => { container = shallow(<LaunchContainer setid={()=>{}} setsuccess={()=>{}} />) });

    it("should render LaunchContainer component", () => {
        expect(container.containsMatchingElement(<Launch setsuccess={()=>{}} setid={()=>{}} data=/>)).toEqual(true);
      });

})

The parent component for which the test is used:

import React from "react";
import { useLaunchesQuery } from "../../generated/graphql";
import Launch from './Launch';

interface Props {
    setid: any;
    setsuccess: any;
}

const LaunchContainer: React.FC<Props> = ({setid, setsuccess}) => {
    const {data, loading, error} = useLaunchesQuery();

    if (loading) {
        return <div>loading...</div>
    }

    if (error || !data) {
        return <div>error</div>
    }

    return <Launch setid={setid} data={data} setsuccess={setsuccess} />
}

export default LaunchContainer;

The child component to be added in test:

import React from "react";
import { LaunchesQuery } from "../../generated/graphql";
import './style.css';

interface Props {
    data: LaunchesQuery;
    setid: any;
    setsuccess: any;
}

const Launch: React.FC<Props> = ({setid, data, setsuccess}) => {
    return (
        <div className="launches">
            <h3>All Space X Launches</h3>
            <ol className="LaunchesOL">
                {!!data.launches && data.launches.map((launch, i) => !!launch && 
                    <li key={i} className="LaunchesItem" onClick={() => {
                        setid(launch.flight_number?.toString())
                        setsuccess(JSON.stringify(launch.launch_success))
                    }}>
                        {launch.mission_name} - {launch.launch_year} (<span className={launch.launch_success? "LaunchDetailsSuccess": launch.launch_success===null? "": "LaunchDetailsFailed"}>{JSON.stringify(launch.launch_success)}</span>)
                    </li>
                )}
            </ol>
        </div>
    );
}

export default Launch;

JMeter recording response is coming in codes

While recording app and web page, Recording response is coming in codes.

enter image description here

Android Tests: No tests found

Starting 0 tests on test(AVD) - 10
Tests on test(AVD) - 10 failed: Instrumentation run failed due to 'Process crashed.'

com.android.build.gradle.internal.testing.ConnectedDevice > No tests found.[test(AVD) - 10] FAILED 
No tests found. This usually means that your test classes are not in the form that your test runner expects (e.g. don't inherit from TestCase or lack @Test annotations).

So I'm running Tests on my CI and this error pops up randomly and sometimes it finds the 2 tests and runs it. But the majority of the time I'm getting this.

I've looked at other answers from Stack Overflow, but they aren't helping me.

How to set timeout for test case in cypress?

enter image description here

The test timed out and can not show in cypress dashboard. How to set timeout for each test case in cypress?

how to test controller failed to save data into database in laravel

I want test my laravel 6 application controller method. One of my controller method is to store data into database. The method code in the controller is like this:

public function store(ContactStoreRequest $request)
    {
        $datas = $request->input();
        $contact = ContactInfo::create($datas);
        if ($contact) {
            return response()->json(['message' => 'success'], 201);
        }
        return response()->json(['message' => 'failed'], 400);
        
    } 

I can test the method by sending a request to the route url like this:

public function test_store_contact_info()
{
    
    $info = factory(ContactInfo::class)->make()->toArray();        
    $response = $this->json('POST', '/api/v1/contact', $info->toArray());
    $response->assertStatus(200);
    $this->assertDatabaseHas('contact_infos', ['email' => $info->email]);
}

Thus I can only test the success stored condition. I want also to test the failed to store data to database( return response()->json(['message' => 'failed'], 400);), How should I do that in the test?

expect(...).toHaveAttribute is not a function - Why?

I created some basic tests and followed the getting started guide on Jests website, but toHaveAttribute is not a function apparently

import React from "react";
import { fireEvent, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

import { App } from "../App";

test("allows users to add items to their list", () => {
  const { getByText, getByLabelText, getByTestId } = render(<App />);

  const input = getByLabelText("What needs to be done?");
  userEvent.type(getByTestId("email"), "Hello World!")
  expect(getByTestId("email")).toHaveAttribute("value", "Hello, World!")
})

TypeError: expect(...).toHaveAttribute is not a function

  10 |   const input = getByLabelText("What needs to be done?");
  11 |   userEvent.type(getByTestId("email"), "Hello World!")
> 12 |   expect(getByTestId("email")).toHaveAttribute("value", "Hello, World!")
     |                                ^
  13 | })

I followed the tutorial exactly so im unsure why this is happening.

How to mock required related entity?

In my problem I want to test PostService class. Every new added post have to have Book (entity) assigned to it first. There is relation OneToMany (one book can have many posts). So if you want to add new post it will be like:

post: {
   "title": "postTitle1",
   "content": "Content of post",
   "bookId": "1"
}

So my savePost method is:

@Transactional
public Post savePost(Post post) {
    Optional<Book> bookOpt = Optional.ofNullable(post.getBook());
    Book bookInPost = bookOpt.orElseThrow(() -> new IllegalArgumentException("Book id for new Post cannot be null!"));
    Book book = bookService.getBook(bookInPost.getId());
    book.addPost(post);
    return postRepository.save(post);
}

Now I want to test this method. How can I mock Book inside Post without inject bookRepository/bookService and without really saving it? Book is also nested (have categories, authors etc.) so it will be hard to make if from 0 every time. I tried something like this:

    @Test
    void should_save_post_assigned_to_book() {
        //given
        Post post = new Post("Title 1", "Content 1");
        Book bookToReturnFromRepository = new Book();
        bookToReturnFromRepository.setId(2);
        //when
        when(mockedBookRepository.findById(any())).thenReturn(Optional.of(bookToReturnFromRepository));
        postService.savePost(post);
        //then
        Optional<Post> loaded = postRepository.findById(post.getId());
        assertAll(() -> {
            assertThat(loaded).isPresent(); ...

But it is obviously wrong. What should I do?

Writing a flutter integration test for logging in using the new package 'integration_test' and getting errors

Writing a flutter integration test for logging in using the new package 'integration_test' and getting errors. It take a long time for the test to start and then exits the app even though it says all tests passed. It doesnt seem to be entering the email and password as well (and if it is then it is going too quick) Any help would be appreciated!

void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();
  //group('App Test', () {

  testWidgets("Sign in test example", (WidgetTester tester) async {
    await tester.runAsync(() async {
      /*
    * Setups the finder*/
      final Finder signInEmailField = find.byKey(Key('email-field'));
      final Finder signInPasswordField = find.byKey(Key('password-field'));
      final Finder signInSaveButton = find.byKey(Key('login-button'));

      //await tester.pumpWidget(app.main());

      await app.main();

      /*
    * pump and settle is same like waitfor in flutter_driver
    * */
      await tester.pumpAndSettle();
      expect(
          find.byWidgetPredicate((Widget widget) =>
              widget is Text && widget.data.startsWith('Login')),
          findsOneWidget);
      final loginFinder = find.byWidgetPredicate((widget) =>
          widget is BusyButton &&
          widget is Text &&
          (widget as Text).data.startsWith('Login'));
      expect(loginFinder, findsOneWidget);
      await tester.tap(loginFinder);
      await tester.pumpAndSettle();
      await tester.tap(find.byKey(Key('email-field')));
      await tester.enterText(signInEmailField, "o.whayman@smartspaces.app");

      await tester.tap(signInPasswordField);
      await tester.enterText(signInPasswordField, "Test1234!");

      await tester.tap(signInSaveButton);
      print("button tapped");

      await tester.pumpAndSettle(Duration(seconds: 1));

      expect(
          find.byWidgetPredicate((widget) => widget is WelcomePagesViewModel),
          findsOneWidget);

      await tester.pumpAndSettle(Duration(seconds: 1));
    });
  });
}
Starting application: integration_test/app_test.dart
Installing build\app\outputs\flutter-apk\app.apk...                 2.4s
Running Gradle task 'assembleDevDebug'...                               
Running Gradle task 'assembleDevDebug'... Done                     19.6s
√ Built build\app\outputs\flutter-apk\app-dev-debug.apk.
I/flutter ( 4526): Observatory listening on http://127.0.0.1:35221/b7p9NQa_6RA=/
E/FlutterFcmService( 4526): Fatal: failed to find callback
VMServiceFlutterDriver: Connecting to Flutter application at http://127.0.0.1:52618/b7p9NQa_6RA=/
VMServiceFlutterDriver: Isolate found with number: 2418217539924163
VMServiceFlutterDriver: Isolate is paused at start.
VMServiceFlutterDriver: Attempting to resume isolate
I/flutter ( 4526): 00:00 +0: Sign in test example
VMServiceFlutterDriver: Connected to Flutter application.
VMServiceFlutterDriver: request_data message is taking a long time to complete...
I/flutter ( 4526): ══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
I/flutter ( 4526): The following assertion was thrown while running async test code:
I/flutter ( 4526): pumpAndSettle timed out
I/flutter ( 4526):
I/flutter ( 4526): When the exception was thrown, this was the stack:
I/flutter ( 4526): #0      WidgetTester.pumpAndSettle.<anonymous closure> (package:flutter_test/src/widget_tester.dart:688:11)      
I/flutter ( 4526): <asynchronous suspension>
I/flutter ( 4526): #1      WidgetTester.pumpAndSettle.<anonymous closure> (package:flutter_test/src/widget_tester.dart)
I/flutter ( 4526): #4      TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:72:41)
I/flutter ( 4526): #5      WidgetTester.pumpAndSettle (package:flutter_test/src/widget_tester.dart:683:27)
I/flutter ( 4526): #6      main.<anonymous closure>.<anonymous closure>
(file:///C:/src/ss-mobile/integration_test/app_test.dart:28:20)
I/flutter ( 4526): <asynchronous suspension>
I/flutter ( 4526): #7      main.<anonymous closure>.<anonymous closure> (file:///C:/src/ss-mobile/integration_test/app_test.dart)   
I/flutter ( 4526): #8      LiveTestWidgetsFlutterBinding.runAsync (package:flutter_test/src/binding.dart:1568:28)
I/flutter ( 4526): #9      WidgetTester.runAsync (package:flutter_test/src/widget_tester.dart:801:17)
I/flutter ( 4526): #10     main.<anonymous closure> (file:///C:/src/ss-mobile/integration_test/app_test.dart:14:18)
I/flutter ( 4526): #11     testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:146:29) 
I/flutter ( 4526): <asynchronous suspension>
I/flutter ( 4526): #12     testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart)        
I/flutter ( 4526): #13     TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:784:19)
I/flutter ( 4526): <asynchronous suspension>
I/flutter ( 4526): #16     TestWidgetsFlutterBinding._runTest (package:flutter_test/src/binding.dart:764:14)
I/flutter ( 4526): #17     LiveTestWidgetsFlutterBinding.runTest (package:flutter_test/src/binding.dart:1592:12)
I/flutter ( 4526): #18     IntegrationTestWidgetsFlutterBinding.runTest (package:integration_test/integration_test.dart:194:17)     
I/flutter ( 4526): #19     testWidgets.<anonymous closure> (package:flutter_test/src/widget_tester.dart:138:24)
I/flutter ( 4526): #20     Declarer.test.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart:175:19)I/flutter ( 4526): <asynchronous suspension>
I/flutter ( 4526): #21     Declarer.test.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart)       
I/flutter ( 4526): #26     Declarer.test.<anonymous closure> (package:test_api/src/backend/declarer.dart:173:13)
I/flutter ( 4526): #27     Invoker.waitForOutstandingCallbacks.<anonymous closure>
(package:test_api/src/backend/invoker.dart:231:15)
I/flutter ( 4526): #32     Invoker.waitForOutstandingCallbacks (package:test_api/src/backend/invoker.dart:228:5)
I/flutter ( 4526): #33     Invoker._onRun.<anonymous closure>.<anonymous closure>.<anonymous closure>
(package:test_api/src/backend/invoker.dart:383:17)
I/flutter ( 4526): <asynchronous suspension>
I/flutter ( 4526): #34     Invoker._onRun.<anonymous closure>.<anonymous closure>.<anonymous closure>
(package:test_api/src/backend/invoker.dart)
I/flutter ( 4526): #39     Invoker._onRun.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart:370:9) 
I/flutter ( 4526): #40     Invoker._guardIfGuarded (package:test_api/src/backend/invoker.dart:415:15)
I/flutter ( 4526): #41     Invoker._onRun.<anonymous closure> (package:test_api/src/backend/invoker.dart:369:7)
I/flutter ( 4526): #48     Invoker._onRun (package:test_api/src/backend/invoker.dart:368:11)
I/flutter ( 4526): #49     LiveTestController.run (package:test_api/src/backend/live_test_controller.dart:153:11)
I/flutter ( 4526): (elided 33 frames from dart:async and package:stack_trace)
I/flutter ( 4526): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter ( 4526): 10:01 +1: (tearDownAll)
I/flutter ( 4526): 10:01 +2: All tests passed!
All tests passed.
Stopping application instance.

Issues with selectors and react 17?

After updating our system's react version, we are having problems with selectors prompting

Cannot read property 'displayName' of null

The code that's breaking:

await t.expect(selector.exists).ok();

we tried appending a timeout inside ok(), it helped but it's still breaking sometimes at that assertion. That selector in particular is defined with ReactSelector, something like this:

selector = ReactSelector('Title').findReact('h1').withProps('children', 'string')

Jest - Mock Hardcoded Array

I want to mock numbers function that exports list of numbers:

// utils.js
export const numbers = () => [1, 2, 3, 4];
export const letters = () => ['x', 'y', 'z'];
// ...and so on

and mock:

// utils.spec.js
jest.mock('utils.js', () => ({
  ...jest.requireActual('utils.js'),
  numbers: jest.fn().mockReturnValue([5, 6, 7]),
})); 

When I run my test case, numbers are still [1, 2, 3, 4]?

Looks like I didn't mock anything?

Dusk tests with VCR mocking

I wish to run Dusk tests while mocking any external requests. Is it possible to configure PHP VCR to work with Laravel Dusk Tests?

I've search any documentation but I didn't find any information...

Testcafe - Loading icon for the hammerhead shadow UI is visible

I am using Testcafe to record a test while uploading a file. Whenever I select the file to upload, the Loading-icon-hammerhead-shadow-ui is triggered

Hammerhead shadow UI icon

Do `go test -coverprofile` working in parallel?

I create some integration testsuites with suite.suite. Each test in testsuite insert some data, witch deletes after test finished:

func (s *myTestSuite) TeardownTest() { s.db.Exec("delete from myTable") }

I expect tests to be executed one after another, so cleaning TeardownTest provide isolation. By tests intersect sometimes. Are tests working in parallel? Transaction with rollback after test seems nice to handle this issue. Is it?

Unit tests fail when using PCOV with --coverage

I have a problem with my unit tests. I’m using PHPUnit 8.5 and Codeception 4.1. My tests run perfectly well when running them normally, but for some reason if I try to generate code coverage the tests immediately stop without any warning or error output.

vendor/codeception/codeception/codecept --ansi run unit --phpunit-xml --no-exit --coverage-xml
Codeception PHP Testing Framework v4.1.16
Powered by PHPUnit 8.5.14 by Sebastian Bergmann and contributors.

Test.unit Tests (1080) --------------------
MBP145:prjct patrick.barbosa$

The tests with coverage also run without problems when I use xdebug instead of PCOV.

Does anyone have any idea what could cause this?

Windows executable not printing to standard output when standard input is redirected from a file

I have a C++ program that I wish to test with certain test cases. I am doing the testing locally. Normally, what I do is create a single test manually, and input it as the standard input for the program, and it prints the output on standard output.

Though the exact code is not very useful here, you can find it here (It's borderline unreadable, please do ask me directly for any queries). The main point being, standard input and output are being used.

So in order to create some test cases and run them on this program, I decided to create another program that creates test cases. Here is it's code:

#include<bits/stdc++.h>
using namespace std ;
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cout<<64<<"\n" ;
    for(int i=0;i<64;i++)
    {
        cout<<"2 3\n" ;
        int a = (i&1)>0 ;
        int b = (i&2)>0 ;
        int c = (i&4)>0 ;
        int d = (i&8)>0 ;
        int e = (i&16)>0 ;
        int f = (i&32)>0 ;
        cout<<a<<b<<c<<"\n";
        cout<<d<<e<<f<<"\n" ;
    }
}

Now let's say the main program has the name BinaryTable.cpp and this test program has the name BinaryTestGen.cpp. So what I do now is :

  1. Compile the main program : g++ -Wall -Wextra -g BinaryTable.cpp -o BinaryTable
  2. Compile the test program : g++ -Wall -Wextra -g BinaryTableGen.cpp -o BinaryTableGen
  3. Now the executables BinaryTable.exe and BinaryTableGen.exe are created (I am using mingw)
  4. Now I redirect the output of the test program to a file BinaryTableTxt.txt by BinaryTableGen.exe > BinaryTableTxt.txt
  5. This creates a 3 KB file BinaryTableTxt.txt
  6. Redirect this file to our main program : BinaryTable.exe < BinaryTableTxt.txt

The output is blank space. Nothing.

Now I run BinaryTable.exe directly, and copy-paste the contents of BinaryTable.txt directly to the cmd, then output is generated.

What am I doing wrong here?

I want the output to be printed to the console even when I am redirecting the input from a file.

In Eclipse while doing appium testing ...How to set JAVA_HOME environment variable for Android Tools to work properly?

Original error: The JAVA_HOME environment variable must be set for Android Tools to work properly

My code:

    DesiredCapabilities capabilities = new DesiredCapabilities();
    
    capabilities.setCapability("BROWSER_NAME", "Android");
    capabilities.setCapability("VERSION", "9.0");

    // ZY224HFLPG is device name
    capabilities.setCapability("deviceName","ZY224HFLPG");
    capabilities.setCapability("platformName","Android"); 

    capabilities.setCapability("appPackage", "com.android.calculator2");
    capabilities.setCapability("appActivity","com.android.calculator2.Calculator"); 

driver = new RemoteWebDriver(new URL("https://ift.tt/3oyke3m), capabilities);

Output:

org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Cannot verify the signature of 'C:\Users\karakris\AppData\Local\Programs\Appium\resources\app\node_modules\appium\node_modules\appium-uiautomator2-server\apks\appium-uiautomator2-server-v4.15.0.apk'.

Original error: The JAVA_HOME environment variable must be set for Android Tools to work properly

Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53' System info: host: 'LIN19003760', ip: '192.168.0.106', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '15.0.1' Driver info: driver.version: RemoteWebDriver remote stacktrace: UnknownError: An unknown server-side error occurred while processing the command. Original error: Cannot verify the signature of 'C:\Users\karakris\AppData\Local\Programs\Appium\resources\app\node_modules\appium\node_modules\appium-uiautomator2-server\apks\appium-uiautomator2-server-v4.15.0.apk'. Original error: The JAVA_HOME environment variable must be set for Android Tools to work properly at getResponseForW3CError (C:\Users\karakris\AppData\Local\Programs\Appium\resources\app\node_modules\appium\node_modules\appium-base-driver\lib\protocol\errors.js:804:9) at asyncHandler (C:\Users\karakris\AppData\Local\Programs\Appium\resources\app\node_modules\appium\node_modules\appium-base-driver\lib\protocol\protocol.js:384:37) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) . . .

WHAT SHOULD HAVE TO DO?

Testing surrounding try catch method with mockito

Im figuring out, how to test this method and force the exception "DataAccessResourceFailureException", but i didn't have a valid way to do it.

I need to force that exception at "ProductRepositoryImpl" class. Any ideas?

ProductRepositoryImpl

  @Override
  public Product saveProduct(Product input) {
  try {
    return productRepositoryAdapter.saveProduct(input);
  } catch (DataAccessResourceFailureException e) {
    logger.error(ERROR_WHEN_SAVING_PRODUCT_DATA_DETAIL + e.getMessage());
  }
    return null;
  }

ProductRepositoryAdapter

  public Product saveProduct(Product input) throws DataAccessResourceFailureException {
    ProductData productData = UtilTransform.productToProductData(input);

    // This method throws exception when there's no connection
    Product createdProduct = productDataRepository.findSkuByCountry(input.getSku(), 
    input.getCountry());

    if (createdProduct == null) {
       return Product.fromModel(productDataRepository.save(productData));
    } else {
      logger.error(THE_PRODUCT_ALREADY_EXISTS_IN_THE_RECORDS);
    }
      return null;
  }

ProductDataRepository

public interface ProductDataRepository extends MongoRepository<ProductData, String> {

  @Query("{'sku': ?0, 'country': ?1}")
  public Product findSkuByCountry(String sku, String country);

  public Optional<ProductData> findById(ProductId id);
}

And my Test, Im using mockito.

@Test
void saveProductException() {
  Mockito.when(productRepository.saveProduct(buildProduct())).thenReturn(buildProduct());
  Mockito.when(adapter.saveProduct(buildProduct())).
      thenThrow(DataAccessResourceFailureException.class);

  Assertions.assertThrows(DataAccessResourceFailureException.class, 
  () -> productRepository.saveProduct(buildProduct()));
}

Error:

org.opentest4j.AssertionFailedError: Expected org.springframework.dao.DataAccessResourceFailureException to be thrown, but nothing was thrown.

How to spy on named function?

I am trying to spy on a named function, exported from the same file from the function I am trying to test. I want to test that function has been called. I want to avoid mocking it completely so that I can have another test for it.

I have utils file like so where I declare my 2 methods

// utils.js
export const myFunction = () => {
  return myOtherFunction()
};

export const myOtherFunction = () => {
  return true
}

I am then testing them here like so:

//utils.test.js
import * as utils from "./utils"

describe("myFunction", () => {
  it("should call myOtherFunction", () => {
    jest.spyOn(utils, "myOtherFunction").mockReturnValue(true)
    const result = utils.myFunction()
    expect(utils.myOtherFunction).toHaveBeenCalledTimes(1)
    expect(result).toEqual(true)
  })
})

It fails because of the following:

Expected number of calls: 1
Received number of calls: 0

Mockito: How to mock WebClient configuring Beans

I'm using Mockio, Wiremock and WebClient. I configured my WebClient to use Oauth via two Bean Methods in a class annotated with @Configuration.

@Configuration
public class WebClientConfig {

    @Bean
    public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
       ...
    }

    /*
    Manages the auth process and token refresh process
     */
    @Bean
    public OAuth2AuthorizedClientManager authorizedClientManager(
            ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientRepository authorizedClientRepository) {

        ...
    }
}

Because I want to use the webClient without oauth to call wiremock, I want to replace the Beans to return a simple Webclient.builder().build();

So I did:

    @MockBean
    WebClientConfig webClientConfig;

and now I'm not sure how to mock the two @Bean annotated methods and where to place them ( in @BeforeAll etc?)

I thought about something like when(webclientConfig).webclient(any(OAuth2AuthorizedClientManager.class)).thenReturn(Webclient.builder.build);

State is always default value when test with another value

Let say I have a component to calculate and display a result from 2 inputs as below. Now I want to test onChange event for input state change.

class CalcForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputFirstNum: 1,
      inputLastNum: 30,
      answer: [10, 20, 30]
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value,
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    this.setState({
    answer: mySampleFunction(this.state.inputFirstNum, this.state.inputLastNum),
  });   
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit} className="container-fluid">
          <input type="number" 
                onChange={this.handleChange} 
                value={this.state.inputFirstNum} />
          <input type="number" 
                onChange={this.handleChange} 
                value={this.state.inputLastNum} />
          <input type="submit" value="Go"/>
        </div>
        <div id="result">
          {this.state.answer.join(', ')}
        </div>   
      </form>
    );
  }
}
export default CalcForm;

Here is my test:

it('should change the value on 1st-input', () => {
  const wrapper = shallow(<CalcForm />);
  wrapper.find('input[type="number"]').at(0).simulate('change', { 
    target: { value: 111 } 
  });
  expect(wrapper.find('input[type="number"]').at(0).prop('value')).toEqual(111);
});

The received is always the default value, as followings:

Expected: 111
Received: 1

Am I missing something?

Testing HOC wrapped React Component

I'm trying to test hoc wrapped component.

The component calls an apollo query inside.

const Header: React.FC<IProps> = ({}) => {
  const { data, loading } = useMeQuery();
  return (
    <>
      {!data?.me.verified && (
        <div className="bg-red-500 p-3 text-center text-sm text-white font-bold">
          <span>Please verify your email</span>
        </div>
      )}
      <header className="py-4">
        <div className="w-full px-5 xl:px-0 max-w-screen-xl bg-yellow-500 mx-auto">
          <Image
            src="/pineapple.png"
            alt="pineapple-logo"
            width="64"
            height="64"
          />
          {data ? (
            <NextLink href="edit-profile">
              <Link>
                <span className="text-sm">
                  <FontAwesomeIcon className="text-xl" icon={faUser} />
                  {data?.me.email}
                </span>
              </Link>
            </NextLink>
          ) : (
            <div>Login</div>
          )}
        </div>
      </header>
    </>
  );
};

export { Header as PureHeader };
export default withApollo()(Header);
import { render, waitFor } from "@testing-library/react";
import React from "react";
import Header, { PureHeader } from "../../src/components/Header";
import { ApolloProvider } from "@apollo/client";
import { createMockClient } from "mock-apollo-client";
import { MockedProvider } from "@apollo/client/testing";
import withApolloMocked from "../../src/apollo/__mock__/withApolloMocked";

describe("<Header />", () => {
  it("renders ok", async () => {
    const mockedClient = createMockClient();
    render(
      <ApolloProvider client={mockedClient}>
        <PureHeader />
      </ApolloProvider>
    );
  });
});

Even if I imported Pure Component without hoc, I get the same error when running the test.

However, if remove the hoc and export default Header (which is a pure component), it then passes the test... ;;;

import React from "react";
import Image from "next/image";
import { useMeQuery } from "../generated/graphql";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faUser } from "@fortawesome/free-solid-svg-icons";
import NextLink from "next/link";
import { Link } from "@chakra-ui/react";
import withApollo from "../apollo/withApollo";

interface IProps {}

const Header: React.FC<IProps> = ({}) => {
  const { data, loading } = useMeQuery();
  return (
    <>
      {!data?.me.verified && (
        <div className="bg-red-500 p-3 text-center text-sm text-white font-bold">
          <span>Please verify your email</span>
        </div>
      )}
      <header className="py-4">
        <div className="w-full px-5 xl:px-0 max-w-screen-xl bg-yellow-500 mx-auto">
          <Image
            src="/pineapple.png"
            alt="pineapple-logo"
            width="64"
            height="64"
          />
          {data ? (
            <NextLink href="edit-profile">
              <Link>
                <span className="text-sm">
                  <FontAwesomeIcon className="text-xl" icon={faUser} />
                  {data?.me.email}
                </span>
              </Link>
            </NextLink>
          ) : (
            <div>Login</div>
          )}
        </div>
      </header>
    </>
  );
};

// export { Header as PureHeader };
// export default withApollo()(Header);
export default Header;
import { render, waitFor } from "@testing-library/react";
import React from "react";
// import Header, { PureHeader } from "../../src/components/Header";
import Header from "../../src/components/Header";
import { ApolloProvider } from "@apollo/client";
import { createMockClient } from "mock-apollo-client";
import { MockedProvider } from "@apollo/client/testing";
import withApolloMocked from "../../src/apollo/__mock__/withApolloMocked";

describe("<Header />", () => {
  it("renders ok", async () => {
    const mockedClient = createMockClient();
    render(
      <ApolloProvider client={mockedClient}>
        <Header />
      </ApolloProvider>
    );
  });
});

Did I miss something? OR Is it just a bug?

I'm not quite sure how to deal with this problem...

Selenium test go too fast and redirect to next page before clicking on element

Selenium test go too fast and redirect to next page before clicking on element

I have the following test : login with multiple users loaded from excel file and create multiple persons which is also loaded from excel file

the problem I meet is that the test goes to create-person page before the login done but when setting Thread.sleep(1000) the test passed

for more clarification here is my code below

@Given("user logged in and populates the form and click create and logout")
public void user_logged_in_and_populates_the_form_and_click_create_and_logout() throws InterruptedException {
    userLoginCreationPage.init();
    logger.info("**************************************** init the driver && go to login page http://localhost:4200/login");

    for (UserLoginPageData userLoginPageData : userLoginPageDataList) {
        logger.info("Line  " + userLoginPageData.getRowIndex() + "from Excel file");
        userLoginCreationPage.enterUsername(userLoginPageData.getUsername());
        userLoginCreationPage.enterPassword(userLoginPageData.getPassword());
        userLoginCreationPage.clickOnLogin();
        Thread.sleep(500);
        logger.info(userLoginPageData.toString() + "is login");
        personCreationPage.init();
        logger.info("**************************************** init the driver && go to creation page http://localhost:4200/dossier-person/new");
        for (PersonPageData personPageData : personPageDataList) {
            if (userLoginPageData.getIdUser().equals(personPageData.getIdUser())) {
                personCreationPage.refresh();
                personCreationPage.enterUsername(personPageData.getUsername());
                personCreationPage.enterEmail(personPageData.getEmail());
                personCreationPage.enterPassword(personPageData.getPassword());
                personCreationPage.clickTab();
                personCreationPage.clickOnCreate();
                logger.info(personPageData.toString() + " ****************************************  is created by " + userLoginPageData.getUsername());
            }
        }
        userLoginCreationPage.clickOnLogout();
    }
}

save screenshots in cypress by docker gitlab ci /cd

i used cypress for test restfull.

after screenshots save but not save !

Is there a way to save screenshots and videos? Or we can log. We could not get any results with

console.log ()
cy.log()
ct.console.log()

in gitlab-ci.ynml :

stages:
  - build
  - test
variables:
  npm_config_cache: "$CI_PROJECT_DIR/.npm"
  CYPRESS_CACHE_FOLDER: "$CI_PROJECT_DIR/cache/Cypress"

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - .npm
    - cache/Cypress
    - node_modules

install:
  image: cypress/base:10
  stage: build

  script:
    - npm ci
    - $(npm bin)/cypress cache path
    - $(npm bin)/cypress cache list
    - $(npm bin)/cypress verify

cypress-e2e:
  image: cypress/base:10
  stage: test
  script:
    - $(npm bin)/cypress run
  artifacts:
    expire_in: 1 week
    when: always
    paths:
    - cypress/screenshots
    - cypress/videos
    reports:
      junit:
        - results/TEST-*.xml

TestCafe, selector is not visible but document.querySelectorAll returns the selector (iframe)

In a TestCafe test I try to switch to an Iframe with the selector bellow:

const iframeCase = Selector('iframe').withAttribute('title', /SR/); 
// I also tried with const iframeCase = Selector("#PegaGadget7Ifr");

But when I run the test, the last test step:

.switchToIframe(iframeCase);

Fails and I receive the following error: The element that matches the specified selector is not visible.

This is the test:

test("First Test", async (t) => {
  await t
    .typeText(username, "this is a username")
    .typeText(password, "this is a password")
    .click(submitButton)
    .click(rocketIconButton)
    .click(caseManager7Button)
    .resizeWindow(1200, 800)
    .click(newCaseButton)
    .click(ServiceRequestButton)
    .switchToIframe(iframeNew)
    .click(doneButton)
    .switchToMainWindow()
    .switchToIframe(iframeCase);
});

When I check the DOM in the debug mode of TestCafe I do see the iframe:

<iframe name="PegaGadget7Ifr" id="PegaGadget7Ifr" border="0" frameborder="0"style="" title="SR-1234" 
data-hammerhead-focused="true"></iframe>

Also when I do a simple document.querySelectorAll('iframe') in the console of the Chrome browser the test is running. It returns the iframe. I also checked if the iframe I'm trying to select is not in a different iframe. But that is not the case.

Did anyone experienced the same issue and what was causing it? Unfortunately I can't share the application under test, since it's is running in a closed corporate environment.

testcafe: 1.10.1
Chrome 87.0.4280.141 / Windows 10.  
node: v14.15.4

I use ab(apache bench) to test my web,but error "apr_socket_connect(): Connection reset by peer (54)" on macOS

code is ab -n 10000 -c 20 http://127.0.0.1:8000/meiduo_admin/statistical/total_count/,but error. error infomation is

Benchmarking 127.0.0.1 (be patient)
Completed 1000 requests
Send request failed!
Completed 2000 requests
Send request failed!
Send request failed!
Completed 3000 requests
Send request failed!
Send request failed!
Send request failed!

Test aborted after 10 failures

apr_socket_connect(): Connection reset by peer (54)
Total of 3965 requests completed

why occur this? I guess concurrence num is too hight.

visulizing miss classified images from CNN

I am visualizing all misclassified images but I am getting the output. But the subplots are really small.

Below is my function. Can someone please help me with what mistake I am doing?.

def visualize_incorrect_labels(test_images, y_real, y_predicted):
    # INPUTS
    # aug_test_images      - images
    # aug_test_classes      - ground truth labels
    # Y_predicted - predicted label
    count = 0
    figure = plt.figure(figsize=(16, 16))
    incorrect_indices = (y_real != y_predicted)
    correct_indices = (y_real == y_predicted)
    y_real = y_real[incorrect_indices]
    y_predicted = y_predicted[incorrect_indices]
    test_images = test_images[incorrect_indices, :, :, :]
    for i, incorrect in enumerate(test_images[:]):
        plt.subplot(6, 3, i + 10)
        plt.imshow(aug_test_images[incorrect], cmap='gray', interpolation='none')
        plt.title("Predicted {}, Truth: {}".format(y_predicted[incorrect], y_real[incorrect]))
        plt.xticks([])
        plt.yticks([])
        plt.show()

How to configure ports of JMeter(Master-Slave) to firewall

Good day! Hi I'm doing distributed testing using JMeter and came up with this confusion. If in case I don't want to disable my firewall, I have to specify the ports needed instead to my firewall. But the thing is, I'm getting confused with the documentation and some tutorials online for their terms such as "server" and "client" and where to apply the configurations to their respective jmeter.properties files. It would have been easy if they used the term "master" and "slave". For instance, I'm confused where to change these ports. Is it for the "master server" or "slave servers"

If you're running JMeter in distributed mode you need to open the following ports: the port you define as server_port, by default 1099 the port you define as server.rmi.localport the ports you define as client.rmi.localport

Please if you have any links or documentations about these configuration let me know to enlighten me.

Unable to Integrate JMeter & Prometheus

Below is my Configuration in Prometheus.yml

Prometheus.yml File

I am Unable to see the Metrics in Browser with localhost:9270 or 127.0.0.1:9270 or with myip:9270. However the same way its working for WMI Exporter (9182) & Prometheus (9090)

Error Faced :- Get "http://localhost:9270/metrics": dial tcp [::1]:9270: connectex: No connection could be made because the target machine actively refused it.. I have even Tried to remove firewall restrictions. Still Facing Same Issue.. Can anyone Help me Out?

mercredi 27 janvier 2021

Testing api with postman

I'm new to api test.I have a project to complete but I don't know much about it.I need to use I need to use postman for testing however my teacher also shared java codes with me.There are classes like base class option class in it.I will test - https://restful-booker.herokuapp.com/.I'm watching the postman lessons now, but I don't understand what java is needed for.Can you help me?I wish everyone my best

How to test Comparator for JUnit test?

I need to test the compare() method and i am confused on how. Can I get advice on how?

public class MemberComparator implements Comparator<Member> {

    private final String clientId;

    public MemberComparator(String clientId) {
        this.clientId = clientId;
    }

    @Override
    public int compare(Member m1, Member m2) {
        if (m1.getClientId().startsWith(clientId)) {
            return m2.getClientId().startsWith(clientId) ? m1.getClientId().compareTo(m2.getClientId())
                    : -1;
        } else {
            return m2.getClientId().startsWith(clientId) ? 1
                    : m1.getClientId().compareTo(m2.getClientId());
        }
    }

}

JMeter - Critical Section Controller accessed by 10 threads at same time

I have single Thread Group A with 100 users that run the following logic:

*REQUEST1 
*REQUEST2
*CRITICAL_SECTION_CONTROLLER 
   -REQUEST3
*TIMER TO WAIT ALL THREADS FINISH
*REQUEST4

I would like to run the REQUEST3 by groups, only for 10 users at same time. (now only one user can at time by the section controller)

Is it possible?

Get and Set a variable from a previous method

Hi Im trying to take a string from an element on a page and then use that string on a later assertion on my selenium test. So basically the element shows the time and then a few minutes later i need to assert that the time hasnt update form the previous time, but this is a differnt method so im trying to save that string and then just check the string mates the new string. Im trying to use getters and setters but they keep changing from public to private on me

So im trying to capture the string using this

public void setDate() {

    date = esfAuthoringDateAndTime.getText();

    this.date = date;
}

and then trying to pass it using this

public String getDate() {

    return date;
}

And the assertion

                esfAuthoringDateAndTimeValue.getText().contains(getDate())

Its just not working for me, any help?

C# Testing. Creating a Mock .csv file upload to filestream

I'm currently creating a function that when a .csv file is uploaded, each field is then read using TextFieldParser. Each field is also validated and the contents of each row are added to a database, with an error displaying to the user if there is a problem with the file. The code validates how many columns (fieldLength), and then each individual column is then validated.

The function works completely fine without issues except I now need to write some tests for the code. I can create a mock filestream, but it fails the validation. Therefore I need to create a mock .csv file with fields that will pass all validation and pass it through as a filestream into the manager.

Any help would be greatly appreciated.

🌞 Why my audio won't get auto-played when testing it with TestCafe? 🌞

I'm trying to test an app using the howler.js library and I need to test if the audio gets auto-played correctly. Apparently, when working with testcafe (even using this command --autoplay-policy=no-user-gesture-required) the audio won't get played automatically. We believe this is because chrome detects it as a screen-reader and gets into account accessibility matters. Could this be the case?

Does anyone know why this is happening or what could be a good way to fix this? Has anyone tried this before?

Thanks and have a nice day! 🌞

Facebook Graph API test user missing email

For my Android unit tests, I use the Facebook Graph API to create test-users and then I log in Facebook with email and password.

Since 2021-02-26, I don't get the test-user's email when I create one with the Facebook API. For example :

POST APP_ID/accounts/test-users

Returns :

{
  "id": "USER_ID",
  "access_token": "SUPER_LONG_ACCESS_TOKEN",
  "login_url": "LOGIN_URL",
  "password": "USER_PASSWORD"
}

So the email is missing now, when I check my user with :

GET /USER_ID (and user's access token)

Returns :

{
  "name": "FIRSTNAME LASTNAME",
  "id": "USER_ID"
}

I checked and my user's have the "email" permission, I also tried my get with "fields=email" but it never returns the email anymore.

So how to get test-user's email from graph API,as before ?

Facebook Graph API test user missing email

For my Android unit tests, I use the Facebook Graph API to create test-users and then I log in Facebook with email and password.

Since 2021-02-26, I don't get the test-user's email when I create one with the Facebook API. For example :

POST APP_ID/accounts/test-users

Returns :

{
  "id": "USER_ID",
  "access_token": "SUPER_LONG_ACCESS_TOKEN",
  "login_url": "LOGIN_URL",
  "password": "USER_PASSWORD"
}

So the email is missing now, when I check my user with :

GET /USER_ID (and user's access token)

Returns :

{
  "name": "FIRSTNAME LASTNAME",
  "id": "USER_ID"
}

I checked and my user's have the "email" permission, I also tried my get with "fields=email" but it never returns the email anymore.

So how to get test-user's email from graph API,as before ?

Allure attachment generate .null file format instead .txt

Below fuction is generating a .null file format in allure report as attachment to test results (it's a browser console errors report), but I want to get a .txt. Is there a way to fix that?

this.getConsoleErrors = async function() {
    var consoleErrors;
    await browser.manage().logs().get('browser').then(function(browserLog) {
        return consoleErrors = require('util').inspect(browserLog);
    });
    await allure.createAttachment('Console logs', function() {return consoleErrors}, 'logs/txt')();
}

Sign in with Google on a non-gmail.com domain gives error: Something went wrong (gmail.googleapis.com)

I'm in test mode with gmail API getting bearer tokens. There is no problem with my app getting authorization when I choose a test user with a gmail.com domain but when I choose a test user with a different domain I get a message "Something went wrong. Sorry, something went wrong there. Try again."

Any insights? Thanks.

React-Native-Testing-Library 'warning - an updated was not wrapped in act(...)

I think this question has been asked, but no solution was provided.

I'm using RNTL trying to unit test a simple RN component.

My example below:

    component = render(<ThemeProvider>
      <NavigationContainer>
        <LandingScreen />
      </NavigationContainer>
    </ThemeProvider>
    );
  });

  afterEach(() => {
    cleanup();
  });


it('renders the main title correcty', async () => {
    const { findByText } = component;
    const heading = await waitFor(() => findByText('Bringing Banking into the Future'));
    expect(heading).toBeTruthy()
  })

I've tried many different waits of using this, without the await waitFor() and I keep getting the same error (see below)

      
      When testing, code that causes React state updates should be wrapped into act(...):
      
      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */

I've also tried all the things mentioned here: https://github.com/callstack/react-native-testing-library/issues/379#issuecomment-714341282, including replacing the findBywith a getBy no luck.

Any ideas would be welcome!

thanks

Chrome extension for selenium video recording

Microsoft Expression Encoder no longer supports video recording from selenium .net.

I have an idea if it's possible to create a chrome extension with a trigger that starts video recording when the browser or tab opens and saves the recorded video after the close.

in selenium it's possible to start chromedriver with enabled extension. but impossible to click on the extension without third-party app. that restricts recording in headless mode.

I have never been worked on extension development. anyone can advise? has my idea chances to become real?

Jest test failing on returning asyncronous method

I'm using TypeORM.
It works fine at the local with real DB connection.

But when I run the test with Jest, the test gets failed.
I mocked the TypeORM method and expected this methods to be called.

but test is failing on expect(typeorm.getRepository(Covid).save).toHaveBeenCalled();

I cannot understand why this test code is failing.

Does anyone know the solution?

Here is the code.

describe('getCoronaData', () => {
  it('should get a Covid Status data and return it', async () => {
    typeorm.getRepository = jest.fn().mockReturnValue({
      findOne: jest.fn().mockResolvedValue(null),
      create: jest.fn(),
      save: jest.fn(),
    });

    await getCoronaData();

    expect(typeorm.getRepository).toHaveBeenCalledWith(Covid);
    expect(typeorm.getRepository(Covid).findOne).toHaveBeenCalled();
    expect(typeorm.getRepository(Covid).save).toHaveBeenCalled(); // this expect result is making an error
                                                                  // Expected number of calls: >= 1
                                                                  // Received number of calls:    0
  });
});
export const getCoronaData = async () => {
  try {
    const covidStatus = [
      {
        city: 'city',
        totalCases: '100',
        increasedCases: '100',
        date: 'time',
      },
    ];
    const covidRepository = getRepository(Covid);
    covidStatus.forEach(async (status) => {
      const exist = await covidRepository.findOne({
        where: { city: status.city },
      });
      if (!exist) {
        return await covidRepository.save(
          covidRepository.create({
            city: status.city,
            totalCases: status.totalCases,
            increasedCases: status.increasedCases,
            date: status.time,
          })
        );
      } else {
        return await covidRepository.save([
          {
            id: exist.id,
            totalCases: status.totalCases,
            increasedCases: status.increasedCases,
            date: status.time,
          },
        ]);
      }
    });
  } catch (err) {
    console.error(err);
    return;
  }
};

Is it possible to transmit error frames on to bus with CANalyzer?

I am looking to transmit error frames onto my CAN bus at a periodic rate for testing purposes. I have CANalyzer and cannot see this as an option anywhere.

I am currently just running a wire from GND to the CAN wires to force errors on the bus but this isn't ideal.

Appreciate any help!

Thanks.

Mobile Performance Testing for Unique ID for particular device,here i am not having the user credentials,How to do user Load testing?

Mobile Performance Testing for Unique ID for a particular device, here I am not having the user credentials, How to do Load testing with different credentials? and Increase more user load?

The following assertion was thrown while resolving an image: Unable to load asset: AssetManifest.json

So, I made a pub.dev flutter package which uses an image asset.

class GoogleIcon extends StatelessWidget {
  final bool isEnabled;

  const GoogleIcon({
    Key key = const Key('google-icon'),
    this.isEnabled = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Opacity(
      opacity: isEnabled ? 1 : 0.5,
      child: Image.asset(
        'assets/google.png',
        key: Key('google-icon-image'),
        package: 'arculus_auth_widgets',
      ),
    );
  }
}

In that library, each of the widget tests run as expected. But when I tried to use the widget in the test of my other package (which depends on it) like this:

  testWidgets('should show buttons at the bottom', (tester) async {
    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: ArculusOnboardingBody(
            buttons: [
              ArculusGoogleButton(label: 'Continue with Google'), // This widget contains GoogleIcon in it
            ],
          ),
        ),
      ),
    );

    await tester.pumpAndSettle(Duration(milliseconds: 100));
  });

It failed with

══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════ The following assertion was thrown while resolving an image: Unable to load asset: AssetManifest.json

When the exception was thrown, this was the stack: #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:225:7) #1 AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:68:33) #2 CachingAssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:167:18) #3 CachingAssetBundle.loadStructuredData (package:flutter/src/services/asset_bundle.dart:188:5) #4 AssetImage.obtainKey (package:flutter/src/painting/image_resolution.dart:176:18) #5 ScrollAwareImageProvider.obtainKey (package:flutter/src/widgets/scroll_aware_image_provider.dart:115:74) #6 ImageProvider._createErrorHandlerAndKey. (package:flutter/src/painting/image_provider.dart:455:15) #10 ImageProvider._createErrorHandlerAndKey (package:flutter/src/painting/image_provider.dart:452:16) #11 ImageProvider.resolve (package:flutter/src/painting/image_provider.dart:330:5) #12 _ImageState._resolveImage (package:flutter/src/widgets/image.dart:1156:16) #13 _ImageState.didChangeDependencies (package:flutter/src/widgets/image.dart:1109:5) #14 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4786:12) #15 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5) ... Normal element mounting (16 frames) #31 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14) #32 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6236:32) ... Normal element mounting (223 frames) #255 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14) #256 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6236:32) ... Normal element mounting (37 frames) #293 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14) #294 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6236:32) ... Normal element mounting (202 frames) #496 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14) #497 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6236:32) ... Normal element mounting (267 frames) #764 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14) #765 Element.updateChild (package:flutter/src/widgets/framework.dart:3324:20) #766 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1252:16) #767 RenderObjectToWidgetElement.update (package:flutter/src/widgets/binding.dart:1230:5) #768 RenderObjectToWidgetElement.performRebuild (package:flutter/src/widgets/binding.dart:1244:7) #769 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5) #770 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2730:33) #771 AutomatedTestWidgetsFlutterBinding.drawFrame (package:flutter_test/src/binding.dart:1088:18) #772 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:302:5) #773 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15) #774 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1055:9) #775 AutomatedTestWidgetsFlutterBinding.pump. (package:flutter_test/src/binding.dart:961:9) #778 TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:72:41) #779 AutomatedTestWidgetsFlutterBinding.pump (package:flutter_test/src/binding.dart:948:27) #780 WidgetTester.pumpWidget. (package:flutter_test/src/widget_tester.dart:524:22) #783 TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:72:41) #784 WidgetTester.pumpWidget (package:flutter_test/src/widget_tester.dart:521:27) #785 main. (file:///Users/moseskarunia/Projects/arculus/test/src/widgets/arculus_onboarding_body_test.dart:67:18) #786 main. (file:///Users/moseskarunia/Projects/arculus/test/src/widgets/arculus_onboarding_body_test.dart:66:52) #787 testWidgets.. (package:flutter_test/src/widget_tester.dart:146:29) #798 FakeAsync.flushMicrotasks (package:fake_async/fake_async.dart:193:32) #799 AutomatedTestWidgetsFlutterBinding.runTest. (package:flutter_test/src/binding.dart:1189:17) #800 AutomatedTestWidgetsFlutterBinding.runTest. (package:flutter_test/src/binding.dart:1177:35) (elided 32 frames from dart:async and package:stack_trace)

Image provider: ScrollAwareImageProvider() Image configuration: ImageConfiguration(bundle: PlatformAssetBundle#2377c(), devicePixelRatio: 3.0, locale: en_US, textDirection: TextDirection.ltr, platform: android) ════════════════════════════════════════════════════════════════════════════════════════════════════ Test failed. See exception logs above. The test description was: should show buttons at the bottom

✖ should show buttons at the bottom Exited (1)

Do you know where did I do it wrong? It behaves correctly in the actual run though (outside of the test)

Thanks.