lundi 30 novembre 2020

Some Typescript test files fail to execute with Mocha and ts-node - "unknown option"

I've been testing my prject for some time with mocha and ts-node with no issues. lately some of the test files started failing on execution returning the following:

error: unknown option '--require'

same result with -r

i'm using the same execution format for all files:

node_modules/mocha/bin/mocha --require ts-node/register ***path to test file***

some files execute correctly and some return the said error.

any thoughts?

Test Note in TestFlight

enter image description here

i want to know where i can give some description to test notes in TestFlight. Because whats in the test information build only shows for the most recent build. And who can change the test note for the build? is it the app owner or the tester?

Purposely slowing a PC down

I am testing a (non-online) game and I cannot react quickly enough to test the higher levels (I am 60 years old and not as quick as I once was...). Is there any way I can slow the CPU to 50 or even 75%?

Can I bypass waiting for the page to load in TestCafe?

Is there a way to bypass the page load wait? The product I am testing is in an iframe, independent of the page that it loads on. However, the host page takes forever to load, unnecessarily increasing my test times. So I am looking for a way to bypass the page load and instead wait on the iframe to finish loading. ideas?

TestCafe, TypeScript

How can i test this @HostListener?

I got this code and i dont know how to test it

@HostListener('document:keydown.escape', ['$event']) onKeydownHandler(event: KeyboardEvent) {
if (this.activeMapTool === this.mapToolEnum.GEOTAG) {
  this.addingGeotag.emit();
}
this.activeMapTool = this.mapToolEnum.NONE;

}

Could you help me?

Only run tests if a variable is larger than a value Cypress

I am trying to only run a set of tests if the version is a certain number or higher in cypress, however I can't seem to make it work correctly. The code below is a bit of an abstraction but shows the overall structure:

if (version < 8203) {
  context('Testing Feature', () => {
    it('Test 1', () => {

    });
    it('Test 2', () => {

    });
    it('Test 3', () => {

    });
  });
else {
  context('Skipping Tests', () => {
    it('Feature Not Available', () => {
      cy.task('log', "Skipping test. Feature not available in this version");
    });
  });
}

I am not sure if this is the correct way to go about this and I have tried several different ways to structure this including putting the if statement in the context but it looks like cypress ignores the if statement or just moves on to the last context and it function.

How do you integrate the log in status in your react test?

I have a React App with protected routes for example /post which I access via the 'link' with name: go to post. Now I am testing this route with:

test('Post links to the correct route [registered]', () => {
        render(<MemoryRouter><App /></MemoryRouter>);
        const link = screen.getByRole('link', { name: /go to post/i });
        userEvent.click(link);
        expect(screen.getByRole('heading', { name: /log in/i })).toBeInTheDocument();

to see if it redirects me to the /login page. It does, but I am wondering what is the best set up for a test with the log in status true for this route? Do I just sign up in the beginning of the test() function?

Laravel (or not) Feature vs Unit Tests

In laravel or none laravel application we have tests like Feature and Unit tests (or whatever, browser, integration they are the same things in different languages as i understood). I read from different places and some of them says that "do not use database operations in your unit tests" and other article gives an example with product creation on unit tests, so i am confused about it and i really want to do it the right way.

For now i just wrote all of my tests as feature tests but i want to separate them my structure is like:

 - Feature
    - Admin
    - Auth
    - Dev (routes that only developers can access)

Until now i had written tests that check CRUD operations and CRUD operations without needed permission (403, no permission returned) and some validation tests like required and valid email, and also login with correct and incorrect credentials.

Which of those should i write as a unit test and also when i separated them should i have the same directory structure as feature tests? Like this:

 - Feature
    - Admin
    - Auth
    - Dev (routes that only developers can access)

- Unit
    - Admin
    - Auth
    - Dev (routes that only developers can access)

Stubbing method using sinon

I am trying to stub a method in sinon.

Here is a simplified example

function a() {
    return b().add(1, 'days);
}

function b() {
   return moment.utc();
}

module.exports = {
  a: a,
  b: b
};

I want to stub function b() to return a specific moment date when called from a file that has required it (e.g. theFile.b()) AND it should also be mocked internally when method a() is called.

I have tried the following

  sinon.stub(theFile, 'b').callsFake(function() {
    console.log("Calling mocked sinon ")
    return moment("2021-10-10", 'YYYY-MM-DD').utc().startOf('day');
  });

Which works when called externally but not when called internally in function a().

I can see this is because sinon is overriding the module export but there must be a way around this. could anyone help?

Stubbing / Spy on global.fetch in Deno

I'm just getting into Deno, one of the things I'm a little unsure about is how to stub or create a spy for the global fetch function?

One solution is to simply wrap the fetch in a function which itself can by stubbed or spied on, but that seems like an unnecessary abstraction.

Any help would be much appreciated.

Spring test controller is throwing exception

This is a really stupid example, but I can't figure out why it does not work. I have the following controller:

public interface CancelController {
  @ResponseStatus(code = HttpStatus.NO_CONTENT)
  @DeleteMapping(path = "/portfolios/{id}/operations/{id2}")
  void cancel(@PathVariable String id, @PathVariable String id2);
}

@RestController
@RequiredArgsConstructor
public class CancelControllerImpl implements CancelController {
  @Override
  public void cancel(String id, String id2) {
    throw new UnsupportedOperationException();
  }
}

and I'm trying to make sure the exception is thrown, for which I created the following test:

class CancelControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @BeforeEach
  void setUp() {
    mockMvc = MockMvcBuilders.standaloneSetup(new CancelControllerImpl()).build();
  }

  @Test
  void cancel() throws Exception {
    assertThrows(UnsupportedOperationException.class, () -> mockMvc.perform(delete("/portfolios/1/operations/1")));
  }
}

The thing is the exception is thrown (I checked it debugging), but the test does not pass. I post here the whole stacktrace of the error:

org.opentest4j.AssertionFailedError: Unexpected exception type thrown ==> expected: <java.lang.UnsupportedOperationException> but was: <org.springframework.web.util.NestedServletException>

    at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:65)
    at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:37)
    at org.junit.jupiter.api.Assertions.assertThrows(Assertions.java:2952)
    at operations.controller.operations.CancelControllerTest.cancel(CancelControllerTest.java:27)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.UnsupportedOperationException
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    at org.springframework.web.servlet.FrameworkServlet.doDelete(FrameworkServlet.java:931)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:523)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:584)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:183)
    at operations.controller.operations.CancelControllerTest.lambda$cancel$0(CancelControllerTest.java:27)
    at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:55)
    ... 66 more
Caused by: java.lang.UnsupportedOperationException
    at operations.controller.operations.CancelControllerImpl.cancel(CancelControllerImpl.java:11)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    ... 76 more

Laravel database testing

This is my first experience with testing in general so sorry for the dummy questions. I was wondering which would be the best practice to write tests in Laravel.

For example, if I want to test database, is it required to make separate db for testing or is it ok to use default db?

I have rest api post call, to test it I pass form data send a request and catch assertion which is ok (200 code, but should be 201 I suppose), is it necessary to test eloquent as well?

How usually this happens, I mean, do I have to write test for each part of project? To test my models do I have to create factories for them all?

Any help would be appreciated!

how to solve Stale Element Reference Exception For this scenario in selenium webdriver java?

I tried all ways that I know in selenium web driver but I could not resolve the issue Stale Element Reference Exception. I tried implicit wait, explicit wait, fluent wait in selenium web driver, but I couldn't resolve this issue.

HTML Code is:: I have to click all li options in this list. if I loop this using both foreach, for, or Iterator I can click the first option, for the second option, it Throws an error as Stale Element Reference Exception.

My selenium code is:

List chapterNames = driver.findElements(By.xpath("//[@id='ctl00_PageContent_ddlreviewCat_DropDown']/child::div/ul/li")); //List chapterQues = driver.findElements(By.xpath("//[@id='ctl00_PageContent_grdReviewDocDetailList_ctl00']/child::tbody/tr/td1")); WebElement ChapterNamedrpdwn = driver.findElement(By.id("ctl00_PageContent_ddlreviewCat_Input")); Thread.sleep(2000); for (int i = 0; i < chapterNames.size(); i++) { try { wait=new WebDriverWait(driver,30); ChapterNamedrpdwn.click(); wait.until(ExpectedConditions.refreshed(ExpectedConditions.visibilityOfAllElements(chapterNames))); chapterNames.get(i).click(); System.out.println(chapterNames.get(i).getAttribute("innerHTML")+ " clicked.."); Thread.sleep(3000); } catch(Exception e) { System.out.println(e.getMessage()); } }

Error Message is: stale element reference: element is not attached to the page document (Session info: chrome=86.0.4240.198) For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/stale_element_reference.html

How to hide suite setup and suite teardown from robot framework log output?

We are using pabot for parallel execution of the tests, but we faced some ugly issue in our logs: suite setup and suite teardown duplicated for every test are shown. If RF has a possibility to hide suite setup and suite teardown from the log?robotframework-log

What are the methods to easily maintain mocked responses that evolve over time?

What are the different options to maintain complex json responses from backend services over time as they evolve?

For example, if I have a complex response that needs many saved version of the json (using fixtures in Cypress... for example). If the response evolves and changes, I will need to update all those json files.

Using mocked json seems like an easy way to set one test data, but I am afraid that over time, I end up with many outdated versions of the response or in need to do tedious updates to the many files when changes happen.

Method 'setMethods' is deprecated when try to write a PHP Unit Test

I want to create a mock to replace a resource:

$gateway = $this->getMockBuilder('PaymentGateway')
            ->setMethods(['transfer'])
            ->getMock();

I got this warning:

Method 'setMethods' is deprecated

How can I resolve this deprecation?

JUnit 4 Test Execution in the order how they are programmed in class

I am using JUnit and RestAssured create API tests.

I was wondering if there is a way to execute test cases in the order how they are written in the class file. Currently when I execute them it seems random.

I tried @TestMethodOrder(MethodOrderer.OrderAnnotation.class) and adding @Order(xy) into the tests but I think that this didn't help me.

Just to describe my problem:

I have multiple tests in the following order in the class: Post tests, Get Tests, Delete tests. As you may already know I want Delete tests to be executed as very last.

Is it possible to do it somehow?

Thanks

Regex testing for 10 non-consecutive numbers

I need to test true or false for 10 non-consecutive numbers.

I have already tried:

function numberCheck(str) {
  let hasTenDigits = /\d{10}/.test(str);
  return hasTenDigits; 
}
console.log(numberCheck("111-111-1111"))

But it returns false since my 10 numbers are not consecutive. How can I go through this little issue?

Enzyme Redux Store integration testing

I am currently trying to perform a full integration test of my redux store using enzyme.

The action "evaluateInput" triggers a Redux saga and the sage will trigger one or two actions which thenb update the state in reducers.

The store I am using for my tests is calling the saga correctly and is also working fine based on the logs that are displayed.

My testing code is the following:

  store.dispatch(evaluateInput('test'));
  const newState = store.getState();
  const expectState = {
    ...initialState,
    success: false,
    inputs: [
      'test'
    ]
  }
  expect(newState).toEqual(expectState);

What I don't understand is that the test above actually succeeds. I am dispatching an action on the store and am retrieving the state on the next row (without subscribing to the store) and it looks like the test actually waits for the saga to complete (I tried adding a 1 second delay in my saga and I could see that the tests were running one second longer but were still succeeding)

It looks like the 2nd row only gets executed once the dispatch action of the first row has finished executing, which is not how store.dispatch() is usually working.

Are the tests in jest/enzyme running only on a single thread or what could be the reason for that behaviour ?

I am actually quite happy about that, but I don't unsderstand it...

How can I test a client-side redirect to a 3rd party site with Cypress?

Cypress offers a simple way to test for server-side redirects using request:

cy.request({
  url: `/dashboard/`,
  followRedirect: false, // turn off following redirects
}).then((resp) => {
  expect(resp.redirectedToUrl).to.eq('http://example.com/session/new')
})

However this doesn't work for client-side redirects because the page is loaded successfully before the redirect happens, meaning the response is for the page, not for the redirect.

How can I test a client-side redirect?

I need a way of catching the redirect and verifying that:

  • it occurred
  • was to the correct URL.

I don't want to follow the redirect away from the app that is being tested.

Fatal error: Uncaught Error: Call to a member function lastName()

question ink: please show Details

Error:

Fatal error: Uncaught Error: Call to a member function lastName() on null in /home/mehdi/Desktop/solution.php:92 Stack trace: #0 {main} thrown in /home/mehdi/Desktop/solution.php on line 92

my answer with problem:

<?php

class Person
{
    private $firstName;
    private $lastName;
    private $age;
    private $father;

    private function __construct(string $firstName = null) {
        $this->firstName = $firstName;
    }

    public static function firstName(string $name = null) {
        return new Person($name);
    }

    public function lastName(string $lastName = null) {
        $this->lastName = $lastName;
        return $this;
    }

    public function age(int $age = null) {
        $this->age = $age;
        return $this;
    }

    public function setFather(Father $father = null) {
        $this->father = $father;
        return $this;
    }

    public function toArray() {

        if (isset($this->firstName) && $this->firstName !== null  &&  strlen($this->firstName) >= 3  &&  strlen($this->firstName) <= 15  && preg_match('/[0-9]/', $this->firstName) == false)
        {
            $this->Person=['firstName'] == $this->firstName;
        }

        if (isset($this->lastName) && $this->lastName !== null  &&  strlen($this->lastName) >= 3  &&  strlen($this->lastName) <= 15  && preg_match('/[0-9]/', $this->lastName) == false)
        {
            $this->Person=['lastName'] == $this->lastName;
        }

        if (isset($this->age) && $this->age >= 1  &&  $this->age <=130   && preg_match('/[0-9]/', $this->age) == false)
        {
            $this->Person=['age'] == $this->age;
        }

        $this->Person=['father' => $this->father->toArray()];

    }
}

class Father
{
    protected static $name;
    protected $family, $age, $result;

    public static function firstName(string $name = null)
    {
        self::$name = $name;
    }

    public function lastName(string $lastName = null)
    {
        $this->family = $lastName;
    }

    public function age(string $age = null)
    {
        $this->age = $age;
    }

    public function toArray()
    {
        if (isset(static::$name) && static::$name !== null && strlen(static::$name) >= 3 && strlen(static::$name) <= 15){
            $this->result['firsName'] = self::$name;
        }

        if (isset($this->family) && $this->family !== null  &&  strlen($this->family) >= 3  &&  strlen($this->family) <= 15  && preg_match('/[0-9]/', $this->family) == false){
            $this->result['lastName'] = $this->family;
        }

        if (isset($this->age) && $this->age !== null && $this->age >= 18 && $this->age <=130 && $this->age > (Person::age() +  18)){
            $this->result['age'] = $this->age;
        }
        return $this->result;
    }
}

$father = Father::firstName('Esaaro')->lastName('Ozaaraa')->age(42);
Person::firstName("Soobaasaa")->lastName( "Ozaaraa")->age(17)
  ->setFather( $father )-> toArray();

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

What does 'the key input state' mean in the Webdriver spec?

I've been trying to digest the Webdriver spec and its more friendly version. And I'm having trouble understanding what do these words mean (in the description of the 'Element Send Keys' command):

The key input state used for input may be cleared mid-way through "typing" by sending the null key, which is U+E000 (NULL)

I had several ideas of what it might mean, I mention some below as a sort of evidence of my 'prior research'*).

Could somebody, please, explain what does it mean and, if possible, give an example, preferably in JavaScript?


*Attempts to figure it out myself: I thought, one may skip calling releaseActions() if he previously pressed, say, the Shift key, like:

await browser.performActions([
  {
    type: 'key',
    id: 'key1',
    actions: [
      { type: 'keyDown', value: '\u0010', },
    ],
  },
]);
await browser.elementSendKeys(elemUUID, '\uE000ABC');

But no, the shift key was still pressed, when the elementSendKeys() was called.

Also I thought the null character clears text in the element, no, it doesn't.

I need expert opinion on planning phase and initial required documentation to develop a small to mid scale system

I have been hired to a brand new IT department with very dysfunctioning management and very inexperienced teamleader/ project manager. My responsibilities for department is as a entry level developer. my team (or just me) have given the task to develop a HR related management system and absolutely mess of a project planning phase. No proper use requirement gathering , system design and etc. this project been dragging along time with no progress what so ever. So im doing my own research to complete necessary steps to complete the initial planning and system design process so me and my fellow developers can start doing our own work. I need a experts guidance and advice on the dumb down version of what essential documentation and diagrams required for me to get to the part where i can code without any complication with me and my other developers.

dimanche 29 novembre 2020

FirebaseError when using jest to test React and Firebase apps

I am trying to do a React test using Jest, but I get the following error.

FirebaseError: projectId must be a string in FirebaseApp.options
      14 | });
      15 | 
    > 16 | export const db = firebase.firestore();
         |                            ^
      17 | export const auth = app.auth();
      18 | export default app;
      19 | export const timestamp = firebase.firestore.FieldValue.serverTimestamp();

      at new FirestoreError (node_modules/@firebase/firestore/src/util/error.ts:216:5)
      at Function.Object.<anonymous>.Firestore.databaseIdFromApp (node_modules/@firebase/firestore/src/api/database.ts:618:13)
      at new Firestore (node_modules/@firebase/firestore/src/api/database.ts:378:36)
      at node_modules/@firebase/firestore/index.node.ts:41:12
      at Component.instanceFactory (node_modules/@firebase/firestore/src/config.ts:78:16)
      at Provider.Object.<anonymous>.Provider.getOrInitializeService (node_modules/@firebase/component/src/provider.ts:194:33)
      at Provider.Object.<anonymous>.Provider.getImmediate (node_modules/@firebase/component/src/provider.ts:95:29)
      at FirebaseAppImpl.Object.<anonymous>.FirebaseAppImpl._getService (node_modules/@firebase/app/src/firebaseApp.ts:127:54)
      at FirebaseAppImpl.firebaseAppImpl.<computed> [as firestore] (node_modules/@firebase/app/src/firebaseNamespaceCore.ts:228:29)
      at Object.firestore (node_modules/@firebase/app/src/firebaseNamespaceCore.ts:209:46)
      at Object.<anonymous> (src/firebase.jsx:16:28)
      at Object.<anonymous> (src/components/HeaderRight.jsx:3:1)
      at Object.<anonymous> (src/components/HeaderRight.test.js:2:1)

It says that the projectId must be a string, so I tried adding "" to the right side of the REACT_APP_FIREBASE_PROJECT_ID in the .env file, but that didn't work.

The following is my test file.

import { HeaderRight } from "./HeaderRight";

test("HeaderRight", () => {
  expect(1+1).toBe(2);
});

If I were to comment out the part where I import HeaderRight, the test would pass. But if I import, it fails.

I also tried the npm install, but it didn't work

The following is my package.json and firebase.jsx.

{
  "name": "firebase-react-auth",
  "version": "0.1.0",
  "homepage": "./",
  "private": true,
  "jest": {
    "testEnvironment": "jest-environment-jsdom-sixteen"
  },
  "dependencies": {
    "@babel/preset-env": "^7.12.7",
    "@babel/preset-react": "^7.12.7",
    "@material-ui/core": "^4.11.0",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/lab": "^4.0.0-alpha.56",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "bootstrap": "^4.5.2",
    "firebase": "^7.20.0",
    "firebase-admin": "^9.3.0",
    "react": "^16.13.1",
    "react-bootstrap": "^1.3.0",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.3",
    "react-test-renderer": "^17.0.1",
    "uuid": "^8.3.1",
    "why-did-you-update": "^1.0.8"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest",
    "eject": "react-scripts eject",
    "format": "prettier --write 'src/**/*.js'"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/plugin-transform-react-jsx": "^7.12.7",
    "@firebase/testing": "^0.20.11",
    "babel-jest": "^26.6.3",
    "enzyme": "^3.11.0",
    "firebase-tools": "^8.15.1",
    "jest": "^26.6.3",
    "jest-environment-jsdom-sixteen": "^1.0.3",
    "prettier": "^2.2.1"
  }
}

import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
import { firestore } from "firebase";

const app = firebase.initializeApp({
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
});

export const db = firebase.firestore();
export const auth = app.auth();
export default app;
export const timestamp = firebase.firestore.FieldValue.serverTimestamp();

I did a lot of research on this error and could not come up with a good answer. If you know something about it, I'd like to know. Thank you for your help.

Jest: How to properly test console.error/console.warn with toThrowError?

How can I test my function calculateAverage will throw an error (console.error) when an empty array is passed?

I'm using Jest to test, but can't get it working with .toThrowError.

calculateAverage.test.tsx:

// Imports: File
const { calculateAverage } = require('../calculateAverage');

// Calculate Average
describe('calculateAverage', () => {
  // Empty Array
  test('Throw Error on empty array', () => {
    expect(calculateAverage([])).toThrowError('Error: Empty Array (calculateAverage)');
  });

  // Test #1
  test('Test #1', () => {
    expect(calculateAverage([1, 2, 3])).toEqual(2);
  });

  // Test #2
  test('Test #2', () => {
    expect(calculateAverage([0, 2, 4, 6, 8, 10])).toEqual(5);
  });
});

calculateAverage.tsx:

// Helper Function: Calculate Average
export const calculateAverage = (array: Array<number>) => {
  // Check If Data Exists
  if (array.length >= 1) {
    // Total
    let total: number = 0;

    // Iterate Over Array
    let i: number = 0;
    while (i < array.length) {
      // Add To Total
      total += array[i];

      // Increase I
      i++;
    }

    return total / array.length;
  }
  else {
    // Error
    console.error('Error: Empty Array (calculateAverage)');
  }
};

Identify Test Technique that can be utilized from the functional requirements and why you choose the test technique?

Functional Requirements

a. The software must allow input of patient data from patient (initial) home, secured access at Physician and Nurse Workstations, and from the data streaming real-time monitoring equipment.

b. The software must request username and password for access to data, only after authentication will allow access to the system.

c. The software must require high levels of error correction and input validation.

d. The software must allow browsing by the physician of historical medical information of his/her patients only.

e. The software must identify the patient by a unique numeric identifier derived from a function performed on the patient’s birth date.

f. The software must retrieve, update, and store data from multiple input locations including but not limited to hospital workstations, physician workstations, inbound emergency vehicles, and electronic monitoring equipment.

g. The software must allow patient to view their own medical record online allowing changes only to address, phone number, and insurer after initial input.

h. The software must only allow deletions by the vendor and only after archiving data in flat file format.

i. The software to be developed must display the correct patient name.

j. The software to be developed shall display the correct time of day in compliance with ISO 8601 k. The software to be developed must operate without interruption twenty-four hours a day.

l. The software must allow full and complete record search queries by physicians; also allow access to limited bloodwork, medication, and allergen information by EMT personnel and display results in order specified by operator.

m. The software must allow input of diagnostic imagery and FAT32 compression for storage and transmission of data.

n. The software must enable output of real-time data and imagery from electronic diagnostic equipment through java applets which run in the web browser.

o. The software must retrieve and sort medical record information and allow for screen and print output of said information

p. The software must encrypt the data using Rijndael (AES) encryption algorithms from the database for transmission from point to point.

I get an error when i test my reducer created with redux

I get this error:

   Reducer "menu" returned undefined during initialization. If the state passed to the reducer is 
   undefined, you must explicitly return
   the initial state. The initial state may not be undefined. If you
   dont want to set a value for this reducer, you can use null instead
   of undefined.

   5 | import { rootReducer } from "./reducers/rootReducer";
   6 | 
>  7 | const reducers = combineReducers({
     |                  ^
   8 |   root: rootReducer,
   9 |   menu: menuReducer,
  10 |   searcher: searchReducer,

  at node_modules/redux/lib/redux.js:378:13
      at Array.forEach (<anonymous>)
  at assertReducerShape (node_modules/redux/lib/redux.js:371:25)
  at combineReducers (node_modules/redux/lib/redux.js:436:5)
  at Object.<anonymous> (src/store/store.ts:7:18)
  at Object.<anonymous> (src/store/actionCreator.ts:1:1)
  at Object.<anonymous> (src/store/initialState.ts:5:1)
  at Object.<anonymous> (src/store/reducers/rootReducer.ts:1:1)
  at Object.<anonymous> (src/tests/rootReducer.test.ts:1:1)

  console.error node_modules/redux/lib/redux.js:325
  No reducer provided for key "root"

  Test Suites: 1 failed, 1 total Tests:       0 total Snapshots:   0
  total Time:        1.175s Ran all test suites related to changed
  files.

when test this reducer (rootReducer.ts):

import { rootInitialState, Reducer, action } from "../initialState";

class RootReducer implements Reducer {
  private initialState: object;

  public constructor(initialState: object) {
    this.initialState = initialState;
  }

  private addNewText = (currentTexts: object, newText: object): object => {
    let newTexts: object = { ...currentTexts };
    newTexts[newText["name"]] = newText["text"];
    return newTexts;
  };

  private switchBodyScroll = (
    payload: "LOCK" | "UNLOCK"
  ): "LOCKED" | "UNLOCKED" => {
    if (payload === "LOCK") {
      document.getElementsByTagName("body")[0].classList.add("scroll-lock");
      return "LOCKED";
    } else {
      document.getElementsByTagName("body")[0].classList.remove("scroll-lock");
      return "UNLOCKED";
    }
  };

  public reduce = (
    state: object = this.initialState,
    action: action
  ): object => {
    if (action.type === "SWITCH_BODY_SCROLL") {
      return {
        ...state,
        bodyScrollState: this.switchBodyScroll(action.payload),
      };
    } else if (action.type === "SWITCH_MINIMAP_MODE") {
      return {
        ...state,
        minimap: {
          ...state["minimap"],
          mode: action.payload.minimapClassList,
          buttonClassList: action.payload.buttonClassList,
        },
      };
    } else if (action.type === "SET_THEMES") {
      return { ...state, themes: [action.payload.items] };
    } else if (action.type === "SET_CURRENT_PAGE") {
      return {
        ...state,
        currentPageId: action.payload.id,
        nextPage: action.payload.next,
        currentPage: [...action.payload.components],
      };
    } else if (action.type === "ADD_NEW_TEXT") {
      return {
        ...state,
        texts: { ...this.addNewText(state["text"], action.payload) },
      };
    } else if (action.type === "SET_PAGE_SEARCHER_VALUE") {
      return { ...state, pageSearcherValue: action.payload };
    } else {
      return state;
    }
  };
}

export const rootReducer = new RootReducer(rootInitialState).reduce;

with this test (rootReducer.test.ts):

import { rootReducer } from "../store/reducers/rootReducer";

it("Body scroll lock should return LOCKED", () => {
  expect(
    rootReducer(undefined, { type: "SWITCH_BODY_SCROLL", payload: "LOCK" })
  ).toBe("LOCKED");
});

store.ts file looks like this:

import { combineReducers, createStore } from "redux";

import { menuReducer } from "./reducers/menuReducer";
import { searchReducer } from "./reducers/searchReducer";
import { rootReducer } from "./reducers/rootReducer";

const reducers = combineReducers({
  root: rootReducer,
  menu: menuReducer,
  searcher: searchReducer,
});

export const store = createStore(reducers);

Of course i have checked out the menu reducer and that one set initial state as default if that was not given. My app work in browser without any errors, I get that only with test. Any imported things are .ts files. Maybe, i just missed something - now i'm learning to work whit jest.

C++ decoding functionality not working properly [closed]

delete this page . this page apparently isn't suitable to posted here.

thanks

testing my code with junit tester did not work i get errors

hi there I am trying to test my code java code with JUnit test case
but there is a problem with the tester I don't know what it is, happy to get from your review and guides

here is the code>>

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class Ex2_Test {
static double[] po1={2,0,3, -1,0}, 
        po2 = {0.1,0,1, 0.1,3};
static final double EPS = 0.0001;

@Test
void testF() {
    double fx0 = Ex2.f(po1, 0);
    double fx1 = Ex2.f(po1, 1);
    double fx2 = Ex2.f(po1, 2);
    assertEquals()
    assertEquals(fx0,2);
    assertEquals(fx1,4);
    assertEquals(fx2,6);
}



@Test
void testRoot() {
    double x12 = Ex2.root(po1, 0, 10, EPS);
    assertEquals(x12, 3.1958, 0.001);
}

@Test
void testDerivativeArrayDoubleArray() {
    double[] p = {1,2,3}; // 3X^2+2x+1
    double[] dp1 = {2,6}; // 6x+2
    double[] dp2 = Ex2.derivative(p);
    assertEquals(dp1[0], dp2[0],EPS);
    assertEquals(dp1[1], dp2[1],EPS);
    assertEquals(dp1.length, dp2.length);
}
}

and here is the errors messages>>

The method assertEquals() is undefined for the type Ex2_Test The import org.junit cannot be resolved

The method assertEquals(double, int) is undefined for the type Ex2_Test

The method assertEquals(double, int) is undefined for the type Ex2_Test

Test cannot be resolved to a type

Test cannot be resolved to a type

The method assertEquals(double, double, double) is undefined for the type Ex2_Test

The method assertEquals(int, int) is undefined for the type Ex2_Test

The method assertEquals(double, double, double) is undefined for the type Ex2_Test

please check the image here>>

here is the tester

How to test android navigation safeargs

Lets say I have 2 fragments: FirstFragment and SecondFragment. I will navigate from FirstFragment to SecondFragment passing through a message argument using safeargs. Where message is just a string.

In my FirstFragment I have a method:

fun navigateToSecond(msg: String){
    var action = FirstFragmentDirections.actionToSecond(msg)
    navController.navigate(action)
}

I can use this method like this:

navigateToSecond("my message")

Then in the SecondFragment I will get the message:

override fun onStart() {
    super.onStart()
    arguments?.let {
        var args = SecondFragmentArgs.fromBundle(it)
        val message = args.message
        // use message here
    }
}

I would like to know is there a way to test this, in particular I would like to test that the appropriate message is sent to SecondFragment when I call navigateToSecond and that SecondFragment correctly receives the message.

I would like to test this using mockito or robolectric.

I tried using mocking to check whether the appropriate methods are called on navController but it was hard and didn't worked out.

So, is there a good or well known way to test the safeargs in android?

Thanks!

best way for UnitTest a flask application

im trying to do a simple unit-test for testing the functionality of the application. The unit-test should create a mock JSON database file (users.json) with predefined data, and validate that the application returns the correct information.

For example, given the following input file:

**

{
    "test_user": {
        "id": "test",
        "name": "Test User",
        "favorite_color": "Black"
    }
}

** (Test #1) Accessing the /users URI should return:

**

{
    "test_user": {
        "name": "Test User",
        "favorite_color": "Black"
    }
}

** (Test #2) Accessing the /user/test_user URI should return:

**

{
    "test_user": {
        "id": "test",
        "name": "Test User",
        "favorite_color": "Black"
    }
}

** (Test #3) Accessing the /user/test_user123 URI should return HTTP code 404 as the user does not exist in the database.

what is the right way to do so?

Mocha testing with mongo fixtures throws me the Timeout of 2000ms exceeded error

I am trying to implement the mocha and chai simple test but I have an error in the response and I cannot figure out why it cannot pass. There are a few questions similar to mine on Stackoverflow and I tried the solutions and advice given there but with no result so I decided to create another question.

What I want to do:

I want to test the request to /api/flasCards endpoint and It should return me two objects:

[
    {
        "_id": "1",
        "front": "hello",
        "back": "czesc"
    },
    {
        "_id": "2",
        "front": "apple",
        "back": "jablko"
    }
]

These objects are added as fixtures(using node-mongodb-fixtures) because I don't want to test it on a real DB. I am making the request in the test file using chai-http. Below you can see the full test file code.

const DB_URI = "mongodb://localhost:27017/flashCard";
const Fixtures = require("node-mongodb-fixtures");
const fixtures = new Fixtures();

const chai = require("chai");
const expect = require("chai").expect;
const chaiHttp = require("chai-http");

const app = require("../src/app");

chai.use(chaiHttp);

const endpoint = "http://localhost:4000/api/flashCard";

describe("FlashCards", () => {
  before((done) => {
    fixtures
      .connect(DB_URI)
      .then((res) => {
        res.unload();
        res.load();
        done();
      })
      .catch((error) => done(error));
  });

  after((done) => {
    fixtures
      .unload()
      .then(() => {
        fixtures.disconnect();
        done();
      })
      .catch(done);
  });

  it("should allow me to get flashcard if I dont have auth token", (done) => {
    console.log("asdasasdasd");

    chai
      .request(app)
      .get(endpoint)
      .then((res) => {
        const body = res.body;

        expect(res.status).to.equal(200);
        expect(body).to.contain.property("front", "hello");
        expect(body).to.contain.property("back", "czesc");
        done();
      })
      .catch((err) => done(err));
  });
});

The response in the console after running the test command is:

$ npm run test

> flashCards@1.0.0 test C:\Users\pstan\Desktop\flashCards
> mocha --require @babel/register --recursive --exit

[info ] Using fixtures directory: fixtures
[info ] No filtering in use
Listening on port 4000


  FlashCards
(node:16760) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.  
[info ] Using database flashCard
asdasasdasd
[start] load flashcards
[done ] unload flashcards
[done ] *unload all
[done ] load flashcards
[done ] *load all
[done ] *script all
    1) should allow me to get flashcard if I dont have auth token
[done ] unload flashcards
[done ] *unload all


  0 passing (2s)
  1 failing

  1) FlashCards
       should allow me to get flashcard if I dont have auth token:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (C:\Users\pstan\Desktop\flashCards\test\flashcards.js)
      at listOnTimeout (internal/timers.js:549:17)
      at processTimers (internal/timers.js:492:7)

When I am adding more timeout: 10000 in the test running command error message is changed to:

 1) FlashCards
       should allow me to get flashcard if I dont have auth token:
     Error: connect ECONNREFUSED 127.0.0.1:80

I don't understand what I am doing wrong here. I am still learning mocha and to do the tests on the backend so I expect that the problem might be my lack of understanding of how it works but I hope you can help me with that.

Fixtures are created in the DB(checked in the mongo compass) and when I am hitting the endpoint in the postman I have the correct response.

Here you can find full app code repo

Integration test with Cypress or React Testing Library?

I'm new to testing and as I understand, integration tests are aimed to test a bunch of components and how they interact with each other.

But if in a project we use both Cypress for E2E and React testing library for unit testing, which one to use for integration tests, and what are the pros and cons?

error in java while running soapui testcases?

Exception in thread "main" java.lang.UnsupportedClassVersionError: com/eviware/s oapui/model/testsuite/TestSuite has been compiled by a more recent version of the Java Runtime (class file version 53.0), this version of the Java Runtime only recognizes class file versions up to 52.0

Jest TypeError: configService.get is not a function

I try to test a new class and the constructor, I have a configService.get.

@Injectable()
export class StripeService {
    private stripe: Stripe;

    constructor(private configService: ConfigService) {
        const secretKey = configService.get<string>('STRIPE_SECRET') || '';
        this.stripe = new Stripe(secretKey, {
            apiVersion: '2020-08-27',
        });
    }
}

And this is my test class :

import { Test, TestingModule } from '@nestjs/testing';
import { StripeService } from './stripe.service';
import { ConfigService } from '@nestjs/config';

const mockStripe = () => ({})

describe('StripeService', () => {
  let service: StripeService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [StripeService,
      { provide: ConfigService, useFactory: mockStripe}
    ],
    }).compile();

    service = module.get<StripeService>(StripeService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});

When i try to run my test I have this error :

enter image description here

If someone have a idea of a solution, i would like to have an explanation.

Thanks,

Nicolas

How to validate the SAML response from cypress

have implemented test for SAML scenario. Here I want to get the SAML response received and validate it. I used cy.server() and cy.rout() methods. But getting error as mentioned below. I used the assertion url as well to rout cy.route("GET", "https://ift.tt/3ocOvF7); But same issue occurred.

Can you explain a way to capture the SAML response within the test to resolve this issue Here is my code:

 cy.server();
        cy.route("GET", "/logincontext?/*").as('route1');
        cy.visit("https://localhost:9443/t/cypress/samlsso?spEntityID=SampleExpressApp");
        cy.get(USERNAME_INPUT).type(username);
        cy.get(PASSWORD_INPUT).type(password,{ log : false });
        cy.contains(CONTINUE_BUTTON).click({ delay: 1500000 }).wait(['@route1'], { timeout: 15000 }).then(xhr => {
            // Do what you want with the xhr object
            cy.writeFile("cypress/fixtures/saml.json",xhr.response);
        }) ;

Cypress execution

SAML Request and response

Debugging airflow tasks using airflow test vs using DebugExecutor

I'm searching for best way to run/debug tasks and dags in my IDE. I see that there are two ways of doing this. I can run airflow test command in debug mode for particular dag and optionally task. Other way is to use DebugExecutor and run particular dag. I see that both ways require that Airflow database is up and running and that all pools are configured (probably queues as well). My questions are:

  1. What is the main difference between these two?
  2. Does airflow test uses DebugExecutor under the hood?
  3. Is there a way to run/debug dags and tasks without running Airflow database and creating dependent pools and queues?

java.lang.RuntimeException: Hilt classes generated from @HiltAndroidTest are missing

I am trying to run a simple Robolectric test with Hilt.

@HiltAndroidTest
@Config(application = HiltTestApplication::class)
@RunWith(AndroidJUnit4::class)
class SplashActivityTest2 {

    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    @Test
    fun fooTest() {
        val splashActivity = ActivityScenario.launch(SplashActivity::class.java)
    }
}

but when I try to run the test using Android Studio, am getting

java.lang.RuntimeException: Hilt classes generated from @HiltAndroidTest are missing. Check that you have annotated your test class with @HiltAndroidTest and that the processor is running over your test

Here's the full stacktrace.

[Robolectric] com.theapache64.nemo.feature.splash.SplashActivityTest2.fooTest: sdk=28; resources=BINARY
Called loadFromPath(/system/framework/framework-res.apk, true); mode=binary sdk=28

java.lang.RuntimeException: Hilt classes generated from @HiltAndroidTest are missing. Check that you have annotated your test class with @HiltAndroidTest and that the processor is running over your test

    at dagger.hilt.android.internal.testing.TestApplicationComponentManager.<init>(TestApplicationComponentManager.java:68)
    at dagger.hilt.android.testing.HiltTestApplication.attachBaseContext(HiltTestApplication.java:39)
    at android.app.Application.attach(Application.java:212)
    at org.robolectric.util.ReflectionHelpers.callInstanceMethod(ReflectionHelpers.java:283)
    at org.robolectric.shadows.ShadowApplication.callAttach(ShadowApplication.java:79)
    at org.robolectric.android.internal.AndroidTestEnvironment.installAndCreateApplication(AndroidTestEnvironment.java:250)
    at org.robolectric.android.internal.AndroidTestEnvironment.setUpApplicationState(AndroidTestEnvironment.java:169)
    at org.robolectric.RobolectricTestRunner.beforeTest(RobolectricTestRunner.java:301)
    at org.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:243)
    at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: dagger.hilt.android.internal.testing.TestComponentDataSupplierImpl
    at org.robolectric.internal.bytecode.SandboxClassLoader.getByteCode(SandboxClassLoader.java:164)
    at org.robolectric.internal.bytecode.SandboxClassLoader.maybeInstrumentClass(SandboxClassLoader.java:119)
    at org.robolectric.internal.bytecode.SandboxClassLoader.lambda$findClass$0(SandboxClassLoader.java:112)
    at org.robolectric.util.PerfStatsCollector.measure(PerfStatsCollector.java:53)
    at org.robolectric.internal.bytecode.SandboxClassLoader.findClass(SandboxClassLoader.java:111)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:419)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:352)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at dagger.hilt.android.internal.testing.TestApplicationComponentManager.<init>(TestApplicationComponentManager.java:58)
    at dagger.hilt.android.testing.HiltTestApplication.attachBaseContext(HiltTestApplication.java:39)
    at android.app.Application.$$robo$$android_app_Application$attach(Application.java:212)
    at android.app.Application.attach(Application.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    ... 11 more


Process finished with exit code 255

Here's my app/build.gradle

Laravel: Class 'App\Http\Requests\Api\BaseFormRequest' not found when I run tests

I am getting this error whenever I run my tests.BaseFormRequest is base class for all the FormRequest class in my app which handles JSON response as per my need. All the tests were running fine few days ago. I had to do a clean OS install. After setting up my OS. I pulled all my projects from BitBucket. install the dependencies in this Laravel project but when starting running tests it started giving me this weird error. Here is the response dump from the test.

#3159
  +"message": "Class 'App\Http\Requests\Api\BaseFormRequest' not found"
  +"exception": "Error"
  +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/app/Http/Requests/StoreTeacherAttendanceRequest.php"
  +"line": 7
  +"trace": array:49 [
    0 => {#3320
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/composer/ClassLoader.php"
      +"line": 444
      +"function": "include"
    }
    1 => {#3458
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/composer/ClassLoader.php"
      +"line": 322
      +"function": "Composer\Autoload\includeFile"
    }
    2 => {#3617
      +"function": "loadClass"
      +"class": "Composer\Autoload\ClassLoader"
      +"type": "->"
    }
    3 => {#3161
      +"function": "spl_autoload_call"
    }
    4 => {#3457
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Support/Reflector.php"
      +"line": 50
      +"function": "class_exists"
    }
    5 => {#1624
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Routing/RouteSignatureParameters.php"
      +"line": 26
      +"function": "isParameterSubclassOf"
      +"class": "Illuminate\Support\Reflector"
      +"type": "::"
    }
    6 => {#3319
      +"function": "Illuminate\Routing\{closure}"
      +"class": "Illuminate\Routing\RouteSignatureParameters"
      +"type": "::"
    }
    7 => {#56
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Routing/RouteSignatureParameters.php"
      +"line": 27
      +"function": "array_filter"
    }
    8 => {#3322
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Routing/Route.php"
      +"line": 491
      +"function": "fromAction"
      +"class": "Illuminate\Routing\RouteSignatureParameters"
      +"type": "::"
    }
    9 => {#53
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Routing/ImplicitRouteBinding.php"
      +"line": 25
      +"function": "signatureParameters"
      +"class": "Illuminate\Routing\Route"
      +"type": "->"
    }
    10 => {#49
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Routing/Router.php"
      +"line": 798
      +"function": "resolveForRoute"
      +"class": "Illuminate\Routing\ImplicitRouteBinding"
      +"type": "::"
    }
    11 => {#57
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php"
      +"line": 39
      +"function": "substituteImplicitBindings"
      +"class": "Illuminate\Routing\Router"
      +"type": "->"
    }
    12 => {#55
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php"
      +"line": 167
      +"function": "handle"
      +"class": "Illuminate\Routing\Middleware\SubstituteBindings"
      +"type": "->"
    }
    13 => {#47
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php"
      +"line": 59
      +"function": "Illuminate\Pipeline\{closure}"
      +"class": "Illuminate\Pipeline\Pipeline"
      +"type": "->"
    }
    14 => {#3619
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php"
      +"line": 167
      +"function": "handle"
      +"class": "Illuminate\Routing\Middleware\ThrottleRequests"
      +"type": "->"
    }
    15 => {#3164
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php"
      +"line": 44
      +"function": "Illuminate\Pipeline\{closure}"
      +"class": "Illuminate\Pipeline\Pipeline"
      +"type": "->"
    }
    16 => {#3616
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php"
      +"line": 167
      +"function": "handle"
      +"class": "Illuminate\Auth\Middleware\Authenticate"
      +"type": "->"
    }
    17 => {#3461
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php"
      +"line": 103
      +"function": "Illuminate\Pipeline\{closure}"
      +"class": "Illuminate\Pipeline\Pipeline"
      +"type": "->"
    }
    18 => {#3618
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Routing/Router.php"
      +"line": 687
      +"function": "then"
      +"class": "Illuminate\Pipeline\Pipeline"
      +"type": "->"
    }
    19 => {#3622
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Routing/Router.php"
      +"line": 662
      +"function": "runRouteWithinStack"
      +"class": "Illuminate\Routing\Router"
      +"type": "->"
    }
    20 => {#3475
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Routing/Router.php"
      +"line": 628
      +"function": "runRoute"
      +"class": "Illuminate\Routing\Router"
      +"type": "->"
    }
    21 => {#3335
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Routing/Router.php"
      +"line": 617
      +"function": "dispatchToRoute"
      +"class": "Illuminate\Routing\Router"
      +"type": "->"
    }
    22 => {#3177
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php"
      +"line": 165
      +"function": "dispatch"
      +"class": "Illuminate\Routing\Router"
      +"type": "->"
    }
    23 => {#3632
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php"
      +"line": 128
      +"function": "Illuminate\Foundation\Http\{closure}"
      +"class": "Illuminate\Foundation\Http\Kernel"
      +"type": "->"
    }
    24 => {#3474
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php"
      +"line": 21
      +"function": "Illuminate\Pipeline\{closure}"
      +"class": "Illuminate\Pipeline\Pipeline"
      +"type": "->"
    }
    25 => {#3334
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php"
      +"line": 167
      +"function": "handle"
      +"class": "Illuminate\Foundation\Http\Middleware\TransformsRequest"
      +"type": "->"
    }
    26 => {#3176
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php"
      +"line": 21
      +"function": "Illuminate\Pipeline\{closure}"
      +"class": "Illuminate\Pipeline\Pipeline"
      +"type": "->"
    }
    27 => {#3336
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php"
      +"line": 167
      +"function": "handle"
      +"class": "Illuminate\Foundation\Http\Middleware\TransformsRequest"
      +"type": "->"
    }
    28 => {#3179
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php"
      +"line": 27
      +"function": "Illuminate\Pipeline\{closure}"
      +"class": "Illuminate\Pipeline\Pipeline"
      +"type": "->"
    }
    29 => {#3337
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php"
      +"line": 167
      +"function": "handle"
      +"class": "Illuminate\Foundation\Http\Middleware\ValidatePostSize"
      +"type": "->"
    }
    30 => {#3634
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php"
      +"line": 63
      +"function": "Illuminate\Pipeline\{closure}"
      +"class": "Illuminate\Pipeline\Pipeline"
      +"type": "->"
    }
    31 => {#3456
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php"
      +"line": 167
      +"function": "handle"
      +"class": "Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode"
      +"type": "->"
    }
    32 => {#3339
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/fideloper/proxy/src/TrustProxies.php"
      +"line": 57
      +"function": "Illuminate\Pipeline\{closure}"
      +"class": "Illuminate\Pipeline\Pipeline"
      +"type": "->"
    }
    33 => {#3182
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php"
      +"line": 167
      +"function": "handle"
      +"class": "Fideloper\Proxy\TrustProxies"
      +"type": "->"
    }
    34 => {#3340
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php"
      +"line": 103
      +"function": "Illuminate\Pipeline\{closure}"
      +"class": "Illuminate\Pipeline\Pipeline"
      +"type": "->"
    }
    35 => {#3480
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php"
      +"line": 140
      +"function": "then"
      +"class": "Illuminate\Pipeline\Pipeline"
      +"type": "->"
    }
    36 => {#3638
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php"
      +"line": 109
      +"function": "sendRequestThroughRouter"
      +"class": "Illuminate\Foundation\Http\Kernel"
      +"type": "->"
    }
    37 => {#3183
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php"
      +"line": 508
      +"function": "handle"
      +"class": "Illuminate\Foundation\Http\Kernel"
      +"type": "->"
    }
    38 => {#3341
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php"
      +"line": 474
      +"function": "call"
      +"class": "Illuminate\Foundation\Testing\TestCase"
      +"type": "->"
    }
    39 => {#3481
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/tests/Feature/TeacherAttendanceManagementTest.php"
      +"line": 48
      +"function": "json"
      +"class": "Illuminate\Foundation\Testing\TestCase"
      +"type": "->"
    }
    40 => {#3639
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/phpunit/phpunit/src/Framework/TestCase.php"
      +"line": 1415
      +"function": "test_teacher_attendance_can_be_taken"
      +"class": "Tests\Feature\TeacherAttendanceManagementTest"
      +"type": "->"
    }
    41 => {#3184
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/phpunit/phpunit/src/Framework/TestCase.php"
      +"line": 1035
      +"function": "runTest"
      +"class": "PHPUnit\Framework\TestCase"
      +"type": "->"
    }
    42 => {#3342
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/phpunit/phpunit/src/Framework/TestResult.php"
      +"line": 691
      +"function": "runBare"
      +"class": "PHPUnit\Framework\TestCase"
      +"type": "->"
    }
    43 => {#3482
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/phpunit/phpunit/src/Framework/TestCase.php"
      +"line": 763
      +"function": "run"
      +"class": "PHPUnit\Framework\TestResult"
      +"type": "->"
    }
    44 => {#3640
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/phpunit/phpunit/src/Framework/TestSuite.php"
      +"line": 597
      +"function": "run"
      +"class": "PHPUnit\Framework\TestCase"
      +"type": "->"
    }
    45 => {#3185
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/phpunit/phpunit/src/TextUI/TestRunner.php"
      +"line": 627
      +"function": "run"
      +"class": "PHPUnit\Framework\TestSuite"
      +"type": "->"
    }
    46 => {#3343
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/phpunit/phpunit/src/TextUI/Command.php"
      +"line": 204
      +"function": "doRun"
      +"class": "PHPUnit\TextUI\TestRunner"
      +"type": "->"
    }
    47 => {#3483
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/phpunit/phpunit/src/TextUI/Command.php"
      +"line": 163
      +"function": "run"
      +"class": "PHPUnit\TextUI\Command"
      +"type": "->"
    }
    48 => {#3641
      +"file": "/home/ropali/.local/share/Trash/files/edu_assit_api/vendor/phpunit/phpunit/phpunit"
      +"line": 61
      +"function": "main"
      +"class": "PHPUnit\TextUI\Command"
      +"type": "::"
    }
  ]
}

My BaseFormRequest.php

<?php

namespace App\Http\Requests\Api;

use Illuminate\Http\JsonResponse;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Foundation\Http\FormRequest as LaravelFormRequest;

abstract class BaseFormRequest extends LaravelFormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    abstract public function rules();

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    abstract public function authorize();

    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        
        throw new HttpResponseException(
            response()->error($validator->messages()->all(), JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
        );
    }
}

My FormRequest

<?php

namespace App\Http\Requests;

use App\Http\Requests\Api\BaseFormRequest;


class StoreTeacherAttendanceRequest extends BaseFormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'attendance_date'  => 'required',
            'in_time'          => 'required',
            'out_time'         => 'required',
            'class'            => 'required',
            'subject'          => 'required',
            'session'          => 'required',
            'teacher_id'       => 'required',
        ];
    }

    /**
     * Check if duplicate entry is being made
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {

            $exist = \App\TeacherAttendance::where([
                'teacher_id'      => request()->teacher_id,
                'attendance_date' => request()->attendance_date,
                'in_time'         => request()->in_time,
                'out_time'        => request()->out_time
            ])->first();

            if (!empty($exist)) {
                $validator->errors()->add('duplicate_attendance', 'Duplicate attendance entry!');
            }

            
        });
    }
}

Actually I am getting this error for all the tests which send request to API which uses BaseFormREquest. I have tried composer dump-autoload few times but not luck. My APIs are working perfectly If send request from POSTMAN. Any help would be appreciated.

samedi 28 novembre 2020

How to create type safe "Recursive" type?

I want to create typed tree sctructure, passing root and child nodes schemas. I expect required properties to be required and optional not to be required, according to schemas, as it must be. However my type test doesn't pass. Here's my piece of code:

type TypedTree<TRootSchema, TChildSchema = TRootSchema> =
  {
    [K in keyof TRootSchema]: TRootSchema[K]
  } | {
    [key: string]: TypedTree<TChildSchema>
  }

const $typeTest = <T>(v: T) => v

// @ts-expect-error Required properies must be present
$typeTest<TypedTree<{ a: number }>>({ })
// 👆 It fails

test junit for coverage with mock

sorry for my english. i have a problem with junit tests. the client asks for coverage for all classes, even for dto / model / entity (even if it's wrong, I have to do it). but i have trouble testing getters and setters. I can't cover, I have tested many solutions but either 0 coverage or in error, what can I do?

my class:

@Entity
 public class AnagrafeUser {

private String firstName; 
private String lastName; 

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
} }

my class test

public class AnagrafeUserTest {

@InjectMocks
private AnagrafeUser anagrafeUser;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
}

@Test
public void setanagrafeUser() throws Exception {
    when(anagrafeUser.getFirstName()).thenReturn("fistname");
    when(anagrafeUser.getLastName()).thenReturn("lastName");

    anagrafeUser.setFirstName("fistname");
    anagrafeUser.setLastName("lastName");
}

always error, for example for last when : 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. tks

setter not coverage.

Julia - When developing a pacakge, how to use an specific dependence only on the test?

I'm developing Julia code for a package, and in my code, the user is free to choose the optimizer he wants, hence, my code does not depend on the many optimizers available. Yet, when I implemented a test set, and to check if the functions are indeed working I need to import an optimizer. My question is then, how to use an specific dependence only on the test? Without making it a dependency on the package itself?

Proper way to test dependencies in FastAPI

Being very new to FastAPI I am strugling to test slightly more difficult code than I saw in the tutorial. I use fastapi_cache module and Redis like this:

from fastapi import Depends, FastAPI, Query, Request
from fastapi_cache.backends.redis import CACHE_KEY, RedisCacheBackend
from fastapi_cache import caches, close_caches

app = FastAPI()

def redis_cache():
    return caches.get(CACHE_KEY)    

@app.get('/cache')
async def test(
    cache: RedisCacheBackend = Depends(redis_cache),
    n: int = Query(
        ..., 
        gt=-1
    )
):  
    # code that uses redis cache

@app.on_event('startup')
async def on_startup() -> None:
    rc = RedisCacheBackend('redis://redis')
    caches.set(CACHE_KEY, rc)

@app.on_event('shutdown')
async def on_shutdown() -> None:
    await close_caches()

test_main.py looks like this:

import pytest
from httpx import AsyncClient
from .main import app

@pytest.mark.asyncio
async def test_cache():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/cache?n=150")

When I run pytest, it sets cache variable to None and test fails. I think I understand why the code is not working. But how do I fix it to test my caching properly?

How to use regex in javascript [duplicate]

How to test if a string matches the follwing regex?


(?!^abstract$|^abstract\..*|.*\.abstract\..*|.*\.abstract$|^assert$|^assert\..*|.*\.assert\..*|.*\.assert$|^boolean$|^boolean\..*|.*\.boolean\..*|.*\.boolean$|^break$|^break\..*|.*\.break\..*|.*\.break$|^byte$|^byte\..*|.*\.byte\..*|.*\.byte$|^case$|^case\..*|.*\.case\..*|.*\.case$|^catch$|^catch\..*|.*\.catch\..*|.*\.catch$|^char$|^char\..*|.*\.char\..*|.*\.char$|^class$|^class\..*|.*\.class\..*|.*\.class$|^const$|^const\..*|.*\.const\..*|.*\.const$|^continue$|^continue\..*|.*\.continue\..*|.*\.continue$|^default$|^default\..*|.*\.default\..*|.*\.default$|^do$|^do\..*|.*\.do\..*|.*\.do$|^double$|^double\..*|.*\.double\..*|.*\.double$|^else$|^else\..*|.*\.else\..*|.*\.else$|^enum$|^enum\..*|.*\.enum\..*|.*\.enum$|^extends$|^extends\..*|.*\.extends\..*|.*\.extends$|^final$|^final\..*|.*\.final\..*|.*\.final$|^finally$|^finally\..*|.*\.finally\..*|.*\.finally$|^float$|^float\..*|.*\.float\..*|.*\.float$|^for$|^for\..*|.*\.for\..*|.*\.for$|^goto$|^goto\..*|.*\.goto\..*|.*\.goto$|^if$|^if\..*|.*\.if\..*|.*\.if$|^implements$|^implements\..*|.*\.implements\..*|.*\.implements$|^import$|^import\..*|.*\.import\..*|.*\.import$|^instanceof$|^instanceof\..*|.*\.instanceof\..*|.*\.instanceof$|^int$|^int\..*|.*\.int\..*|.*\.int$|^interface$|^interface\..*|.*\.interface\..*|.*\.interface$|^long$|^long\..*|.*\.long\..*|.*\.long$|^native$|^native\..*|.*\.native\..*|.*\.native$|^new$|^new\..*|.*\.new\..*|.*\.new$|^package$|^package\..*|.*\.package\..*|.*\.package$|^private$|^private\..*|.*\.private\..*|.*\.private$|^protected$|^protected\..*|.*\.protected\..*|.*\.protected$|^public$|^public\..*|.*\.public\..*|.*\.public$|^return$|^return\..*|.*\.return\..*|.*\.return$|^short$|^short\..*|.*\.short\..*|.*\.short$|^static$|^static\..*|.*\.static\..*|.*\.static$|^strictfp$|^strictfp\..*|.*\.strictfp\..*|.*\.strictfp$|^super$|^super\..*|.*\.super\..*|.*\.super$|^switch$|^switch\..*|.*\.switch\..*|.*\.switch$|^synchronized$|^synchronized\..*|.*\.synchronized\..*|.*\.synchronized$|^this$|^this\..*|.*\.this\..*|.*\.this$|^throw$|^throw\..*|.*\.throw\..*|.*\.throw$|^throws$|^throws\..*|.*\.throws\..*|.*\.throws$|^transient$|^transient\..*|.*\.transient\..*|.*\.transient$|^try$|^try\..*|.*\.try\..*|.*\.try$|^void$|^void\..*|.*\.void\..*|.*\.void$|^volatile$|^volatile\..*|.*\.volatile\..*|.*\.volatile$|^while$|^while\..*|.*\.while\..*|.*\.while$)(^(?:[a-z_]+(?:\d*[a-zA-Z_]*)*)(?:\.[a-z_]+(?:\d*[a-zA-Z_]*)*)*$)

How to fetch multiple key-value pairs array in Java Script/TestCafe

const passnegerGroup = [
  { FIRSTNAME: 'RAHUL', LASTNAME: 'KUMAR' },
  { FIRSTNAME: 'RINA', LASTNAME: 'KUMAR' },
  { FIRSTNAME: 'SOHAN', LASTNAME: 'SINGH' },
  { FIRSTNAME: 'PAUL', LASTNAME: 'ANDERSON' },
];

// I want to read each passenger's last name and first name and do some operations.

// Tried this code but this is

for (const key of Object.values(passnegerGroup)) {
  console.log(key.FIRSTNAME, key.LASTNAME);
}

output :

RAHUL KUMAR RINA KUMAR SOHAN SINGH PAUL ANDERSON

This is working for but getting ESLINT error. ESLint: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.(no-restricted-syntax)

Kindly help me achieve the above using some modern JavaScript/TestCafe codes

Cypress throwing SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' (17:0)

I am trying to use cypress select tests but facing the following exception. Did anyone face this issue before?

cypress/plugins/index.ts

const TC_GROUPING = require('cypress-select-tests/grep')

module.exports = (on, config) => {
    
    require('cypress-terminal-report/src/installLogsPrinter')(on, {
            printLogsToConsole: 'always'
        }
    )
    
    on('file:preprocessor', TC_GROUPING(config))

    on('task', {
        // Returns the customer Object of type: Customer
        createCustomer: () => {
            console.log("This is Sample Function")
        }
    })

    return config
}

Error Message:

SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' (17:0)
    at Parser.pp$4.raise (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:2927:15)
    at Parser.pp$1.parseStatement (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:870:18)
    at Parser.pp$1.parseTopLevel (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:755:23)
    at Parser.parse (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:555:17)
    at Function.parse (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:578:37)
    at Object.parse (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:5143:19)
    at module.exports (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/falafel/index.js:23:22)
    at Object.findTests (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/cypress-select-tests/src/spec-parser.js:95:3)
    at process (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/cypress-select-tests/src/itify.js:18:33)
    at Stream.onend (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/cypress-select-tests/src/itify.js:52:18)
    at _end (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/through/index.js:65:9)
    at Stream.stream.end (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/through/index.js:74:5)
    at DestroyableTransform.onend (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:577:10)
    at Object.onceWrapper (events.js:416:28)
    at DestroyableTransform.emit (events.js:322:22)
    at endReadableNT (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:1010:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)

Error: The following error was thrown by a plugin. We stopped running your tests because a plugin crashed. Please check your plugins file (`/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/cypress/plugins/index.ts`)
    at Object.get (/private/tmp/cypress_cache/5.4.0/Cypress.app/Contents/Resources/app/packages/server/lib/errors.js:968:15)
    at EventEmitter.handleError (/private/tmp/cypress_cache/5.4.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/index.js:159:20)
    at EventEmitter.emit (events.js:310:20)
    at ChildProcess.<anonymous> (/private/tmp/cypress_cache/5.4.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/util.js:19:22)
    at ChildProcess.emit (events.js:310:20)
    at emit (internal/child_process.js:876:12)
    at processTicksAndRejections (internal/process/task_queues.js:85:21)

Added the following lines in plugins/index.ts as mentioned in blog: https://en.it1352.com/article/1963119.html but no luck. Did anyone encounter this issue?

    const options = {
        // send in the options from your webpack.config.js, so it works the same
        // as your app's code
        webpackOptions: require('../../webpack.config'),
        watchOptions: {}
    }

    on('file:preprocessor', web_pack(options))

webpack.config.js

const path = require('path');

module.exports = {
    entry: './src/index.ts',
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            },
        ],
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
};

Testing content providers with ProviderTestCase2

I am trying to test my content provider following the snippet in this answer

https://stackoverflow.com/a/35680611/12652258

The post mentions that the Test must not be run with AndroidJUnit4 runner -Test of course must be run as android instrumented test

How do I achieve this ?

1: Running an instrumented test without using AndroidJUnit4 runner ?

2: Where do I place the test files in my project? In the test folder or androidTest folder ?

vendredi 27 novembre 2020

intercept restful API with cypress in a ssr next.js project using axios

I'm trying to write some tests with cypress and fixtures on my ssr next.js app that connects to restful api using axios. But I'm having trouble intercepting the restful apis using cy.intercept() because cypress can not track the requests that are sent in ssr and cy.intercept() only works on requests that cypress can track. Is there any packages that can help me change the responses coming from restful api?

A better way to select elements for UI testing Svelte

I'm looking for framework like vue hubble for svelte.js. please share me a link if it is already available.

@Test gives unresolved reference - Kotlin

//kotlin snippet:
import kotlin.test.*
import kotlin.test.assertEquals

sealed class Transport
data class Train(val line: String) : Transport()

fun travel(transport: Transport) = "Train S1"

class TestTest {
@Test
fun `train travel`() {
    assertEquals("Train S1", travel(Train("S1")))
}
}

enter code heremain(){} //The dependencies are: /* dependencies { in build.gradle testCompile group: 'junit', name: 'junit', version: '4.12' testImplementation "org.jetbrains.kotlin:kotlin-test-common" testImplementation "org.jetbrains.kotlin:kotlin-test" testImplementation "org.jetbrains.kotlin:kotlin-test-junit" testImplementation "org.jetbrains.kotlin:kotlin-test-junit5" testImplementation "org.junit.jupiter:junit-jupiter:$junit_version" }*/

//Using IntelliJ 2020.2.3 Build Oct 6 2020 Version 11.0.8
//Why is compiler giving unresolved reference on @Test statement

How testing my API calls in differents groups of test?

Im starting with react-testing-library, and Im trying to test API calls. I have two sets, one for success request and another for error request.

import React from "react";
import { render, waitForElementToBeRemoved } from "@testing-library/react";
import user from "@testing-library/user-event";
import App from "./App";
import { getUser } from "./serviceGithub";

jest.mock("./serviceGithub");

//Mock data for success and error, Im using the github api
const dataSuccess = {
    id: "2231231",
    name: "enzouu",
};

const dataError = {
    message: "not found",
};

const renderInit = () => {
    const utils = render(<App />);
    const inputUser = utils.getByPlaceholderText("ingrese usuario", {
        exact: false,
    });
    const buttonSearch = utils.getByRole("button", { name: /buscar/i });

    return { utils, buttonSearch, inputUser };
};

test("should success request to api", async () => {
    getUser.mockResolvedValue([dataSuccess]);
    const { utils, buttonSearch, inputUser } = renderInit();
    expect(utils.getByText(/esperando/i)).toBeInTheDocument();
    expect(buttonSearch).toBeDisabled();
    user.type(inputUser, "enzzoperez");
    expect(buttonSearch).toBeEnabled();
    user.click(buttonSearch);
    await waitForElementToBeRemoved(() =>
        utils.getByText("cargando", { exact: false })
    );
    expect(getUser).toHaveBeenCalledWith("enzzoperez");
    expect(getUser).toHaveBeenCalledTimes(1);
    expect(utils.getByText("enzouu", { exact: false })).toBeInTheDocument();
});

test("should error request to api", async () => {
    getUser.mockResolvedValue(dataError)
    const { utils, buttonSearch, inputUser } = renderInit();
    expect(buttonSearch).toBeDisabled();
    user.type(inputUser, "i4334jnrkni43");
    expect(buttonSearch).toBeEnabled();
    user.click(buttonSearch)
    await waitForElementToBeRemoved(()=>utils.getByText(/cargando/i))
    expect(getUser).toHaveBeenCalledWith('i4334jnrkni43')
    expect(getUser).toHaveBeenCalledTimes(1)
});

The problem here is that in the second test the last line expect(getUser).toHaveBeenCalledTimes(1) get error because getUseris calling 2 times, but if I comment the first test, the second pass..

So, how should I do to test this case? Its ok the way that Im doing the tests?

Thanks!

Jest and RTL to test a input type image file

Is there a way to use jest and RTL to input an image file, most examples i am seeing online is mocking a file by by using a string; however, I am trying to upload an image file which will then be compressed and then convert into base64 and finally display it on the DOM.

  function imageFileHandler(file) {
    setDisplay(file);
    toBase64(file).then((data) => setSelectedFile(data));
  }

  function imageCompressor(event) {
    const file = event.target.files[0];
    console.log(typeof file)
    const options = {
      maxSizeMB: 0.05,
      maxWidthOrHeight: 700,
      useWebWorker: true,
    };
    imageCompression(file, options)
      .then((compressedFile) => {
        console.log(compressedFile);
        imageFileHandler(compressedFile);
      })
      .catch(() => setErrorForm('unable to convert image file'));
  }

Jest with node.JS Express causing open handle error

I have a basic node.JS Express app server, and when I try running Jest jest --detectOpenHandles, I get the following error. I'm not sure what could be causing it though, since as far as I'm aware, I make sure to close the server once all the tests complete.

Error message

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ●  TCPSERVERWRAP

      18 |  * Listen on provided port, on all network interfaces.
      19 |  */
    > 20 | server.listen(process.env.PORT);
         |        ^
      21 | server.on('listening', onListening);
      22 | 
      23 | /**

      at Object.<anonymous> (index.ts:20:8)

index.ts

#!/usr/bin/env node

import { app } from './app'
import http from 'http'
import {AddressInfo} from "net";

export const server = http.createServer(app);

server.listen(process.env.PORT);
server.on('listening', onListening);

function onListening() {
    const addr = server.address() as AddressInfo;
    const bind = 'port ' + addr.port;

    console.log(`Listening on ${bind}`)
}

jest.config.ts

export default {
  bail: true,
  clearMocks: true,
  globalTeardown: "./tests/helpers/server_close.ts",
  roots: [
    "./tests"
  ],
  testEnvironment: "node",
  watchman: true,
};

tests/helpers/server_close.ts

import {server} from "../../index";

export default async () => {
    await server.close();
}

tests/webhook.test.ts

// imports

const request = supertest(app);

beforeAll(async (done) => {
    const url = `mongodb://127.0.0.1/test`
    await mongoose.connect(url, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    done();
});

afterAll(async (done) => {
    await mongoose.disconnect();
    done();
})

afterEach(async (done) => {
    await User.deleteMany({});
    await Installation.deleteMany({});
    done();
})

test('webhook receive event valid', async (done) => {
    const response = await request.post('/receive-webhook')
        .set({
            'X-GitHub-Event': 'pull_request',
            'X-GitHub-Delivery': '1'
        })
        .send(FakeData.makePullRequestPayload('opened', false))

    expect(response.status).toBe(HTTPStatusCode.OK);

    done()
})

Versions:

  • node v14.10.1
  • express v4.16.1
  • jest v26.6.3

(Adding some more text since SO says my post is mostly code)

Change fixture response in cypress for the same url with intercept

I am trying to write a test with the new cypress 6 interceptor method (Cypress API Intercept). For the test I am writing I need to change the reponse of one endpoint after some action was performed.

Expectation:

I am calling cy.intercept again with another fixture and expect it to change all upcomming calls to reponse with this new fixture.

Actual Behaviour:

Cypress still response with the first fixture set for the call.

Test Data:

In a test project I have recreated the problem:

test.spec.js

describe('testing cypress', () => {


    it("multiple responses", () => {

        cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' });

        // when visiting the page it makes one request to http://localhost:4200/testcall
        cy.visit('http://localhost:4200');
        cy.get('.output').should('contain.text', '111');

        // now before the button is clicked and the call is made again
        // cypress should change the response to the other fixture
        cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' });

        cy.get('.button').click();
        cy.get('.output').should('contain.text', '222');
        
    });

});

example.json

{
  "text": "111"
}

example2.json

{
  "text": "222"
}

app.component.ts

import { HttpClient } from '@angular/common/http';
import { AfterViewInit, Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  public text: string;

  public constructor(private httpClient: HttpClient) { }

  public ngAfterViewInit(): void {
    this.loadData();
  }

  public loadData(): void {
    const loadDataSubscription = this.httpClient.get<any>('http://localhost:4200/testcall').subscribe(response => {
      this.text = response.body;
      loadDataSubscription.unsubscribe();
    });
  }

}

app.component.html

<button class="button" (click)="loadData()">click</button>

<p class="output" [innerHTML]="text"></p>