mardi 31 décembre 2019

How to unit test location services pop up in Android

I'm really trying to wrap my head around unit testing. Could use a little help for a road block. I'm trying to click the location popup buttons when asking for location permissions. I'm using JUnit 4 and expresso. Here's my test rule:

@get:Rule
val testRule: ActivityTestRule<MyActivity> = ActivityTestRule(MyActivity::class.java)

I got a set up function:

@Before
fun setUp() {
    mActivity = testRule.activity
    mFragment = MyFragment.newInstance()
}

And finally my button click test:

@Test
fun testLocationClick(){
    Assert.assertNotNull(onView(withId(R.id.button_turn_on_location)))
    onView(withId(R.id.button_turn_on_location)).perform(click())

    onView(withText("Allow all")).perform(click())

This last line saying "Allow all" was my attempt to try and click on the allow button but it does not work. Here's an attached image showing what I'm trying to click. Image

How to test environment variables configured on Heroku settings

I have a Heroku's CI configured for my app, so what I tried was to test the ENV variables that I have already configured in the settings of Heroku (I want to check if they are correct) as part of my test suites. As you know, this test step runs before the deploy. The problem was that the test was unable to access those variables, it couldn't find them. A I understood, those variables are only accessed by the app during run-time, maybe I'm wrong.

Can you suggest me some workaround in which in can check the ENV variables configured before Heroku deploys my apps?

How do I test an Express.js app with AVA?

I can test my models fine with AVA, but I would like to also test the routes.

I feel it should be possible to access the Express app object, and pass it a URL, then see what comes back, but I do not know how to get the Express object to use it.

Testing Android app behavior when an exception occur

How can i test my android app behavior when an exception occur? I am using jUnit for unit & instrumented tests. Now i want to add some scenario with exception,is there any solution to test my app behavior in this case (app crashs or not, warning/message/toast is displayed, ...) ?

Symfony Test - null token with Guard Authentication

I have a Guard Authentication in my Symfony Web Application. I would like to perform some unit tests. I'm unable to simulate an authentification in my test. The token stays null when calling $tokenStorage->getToken().

Note:

  • The login authentification is working under dev and prod environnement.
  • I saw quite a lot of related topics without success and the doc as well.
  • Symfony version: 3.4.

Reproduce: you can reproduce the error from this repo (symfony project).

Code sample:

After manually creating an User, the login function used in tests:

private function logIn($firewallName = 'main'){
   // dummy call to bypass the hasPreviousSession check
   $crawler = $this->client->request('GET', '/');
   $session = $this->client->getContainer()->get('session');

   /** @var User $user */
   $user = $this->entityManager->getRepository(User::class)
       ->findOneBy(['email' => 'user1@example.com']);

   // you may need to use a different token class depending on your application.
   // for example, when using Guard authentication you must instantiate PostAuthenticationGuardToken
   $token = new PostAuthenticationGuardToken($user, $firewallName, [new Role('ROLE_CLIENT')]);
        self::$kernel->getContainer()->get('security.token_storage')->setToken($token);

   $session->set('_security_'.$firewallName, serialize($token));
   $session->save();

   $cookie = new Cookie($session->getName(), $session->getId());
   $this->client->getCookieJar()->set($cookie);
}

The User call from tokenStorage (from service function):

class ExampleValidator extends ConstraintValidator{
    protected $requestStack;
    protected $em;
    protected $user_id;

    public function __construct(RequestStack $request,
                                EntityManager $em,
                                TokenStorage $tokenStorage){
        $this->requestStack = $request;
        $this->em = $em;

        /** @var User $user */
        // Token is always null
        $user = $tokenStorage->getToken()->getUser();
        $this->user_id = $user != "anon." ? $user->getId() : null;
    }

    /**
     * @param $value
     * @param Constraint $constraint
     */
    public function validate($value, Constraint $constraint)
    {
        // validation rules ...
    }
}

LoginFormAuthenticator.php

<?php

namespace AppBundle\Security;


use AppBundle\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Http\Util\TargetPathTrait;

class LoginFormAuthenticator extends AbstractFormLoginAuthenticator{
    use TargetPathTrait;

    private $entityManager;
    private $urlGenerator;
    private $csrfTokenManager;
    private $passwordEncoder;
    private $loginAttemptRepository;


    public function __construct(EntityManagerInterface $entityManager,
                                UrlGeneratorInterface $urlGenerator,
                                CsrfTokenManagerInterface $csrfTokenManager,
                                UserPasswordEncoderInterface $passwordEncoder){
        $this->entityManager = $entityManager;
        $this->urlGenerator = $urlGenerator;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->passwordEncoder = $passwordEncoder;
    }

    /**
     * @param Request $request
     * @return bool
     */
    public function supports(Request $request){
        return $request->getPathInfo() == '/login_check' &&
            $request->isMethod('POST') &&
            $request->request->get('_password') !== null;
    }


    /**
     * @param Request $request
     * @return array|mixed|void|null
     */
    public function getCredentials(Request $request){
        $isLoginSubmit = $request->getPathInfo() == '/login_check' &&
            $request->isMethod('POST') &&
            $request->request->get('_password') !== null;
        $isCaptcha = $request->request->get('captcha_set');

        if ($isCaptcha == 1 && $request->request->get('_password') !== null) {
            $secret = ...;
            if($_POST['g-recaptcha-response'] !== null){
                // Paramètre renvoyé par le recaptcha
                $response = $_POST['g-recaptcha-response'];
                $remoteip = $_SERVER['REMOTE_ADDR'];

                $api_url = "https://www.google.com/recaptcha/api/siteverify?secret="
                    . $secret
                    . "&response=" . $response
                    . "&remoteip=" . $remoteip ;

                $decode = json_decode(file_get_contents($api_url), true);

                if ($decode['success'] == true) {
                    $username = $request->request->get('_username');
                    $password = $request->request->get('_password');
                    $csrfToken = $request->request->get('_csrf_token');

                    if (false === $this->csrfTokenManager->isTokenValid(new CsrfToken('authenticate', $csrfToken))) {
                        throw new InvalidCsrfTokenException('Invalid CSRF token.');
                    }

                    $request->getSession()->set(
                        Security::LAST_USERNAME,
                        $username
                    );

                    return [
                        'username' => $username,
                        'password' => $password,
                    ];
                }
                else{
                    throw new CustomUserMessageAuthenticationException('Captcha invalids.');
                }
            }
            else{
                throw new CustomUserMessageAuthenticationException('Captcha invalids.');
            }
        }
        else {
            if (!$isLoginSubmit) {
                // skip authentication
                return;
            }

            $username = $request->request->get('_username');
            $password = $request->request->get('_password');
            $csrfToken = $request->request->get('_csrf_token');

            if (false === $this->csrfTokenManager->isTokenValid(new CsrfToken('authenticate', $csrfToken))) {
                throw new InvalidCsrfTokenException('Invalid CSRF token.');
            }

            $request->getSession()->set(
                Security::LAST_USERNAME,
                $username
            );

            return [
                'username' => $username,
                'password' => $password,
            ];
        }
    }

    /**
     * @param mixed $credentials
     * @param UserProviderInterface $userProvider
     * @return User|object|UserInterface|null
     */
    public function getUser($credentials, UserProviderInterface $userProvider){
        $username = $credentials["username"];
        $user = $this->entityManager->getRepository(User::class)
            ->findOneBy(['username' => $username]);
        return $user;
    }


    /**
     * @param mixed $credentials
     * @param UserInterface $user
     * @return bool
     */
    public function checkCredentials($credentials, UserInterface $user){
        $password = $credentials["password"];
        $rep = false;
        if ($this->passwordEncoder->isPasswordValid($user, $password)){
            $rep = true;
        }
        return $rep;
    }

    /**
     * @param Request $request
     * @param TokenInterface $token
     * @param string $providerKey
     * @return RedirectResponse
     */
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey){
        $targetPath = null;
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }
        return new RedirectResponse($this->urlGenerator->generate('map'));
    }

    /**
     * @return string
     */
    protected function getLoginUrl(){
        return $this->urlGenerator->generate('fos_user_security_login');
    }
}

How run tests on Heroku with Maven

How do I run tests on Java Maven app on Heroku. I am using autodeploy linked to a branch on Github.

The default Maven command run on Heroku is: mvn -DskipTests clean dependency:list install

To remove the skipTests, I set the MAVEN_CUSTOM_OPTS as described on https://github.com/heroku/heroku-buildpack-java#customize-maven.

However this does not result on the tests to be run. Looking at the build log I can see:

[INFO] --- maven-compiler-plugin:3.8.1:testCompile (java-test-compile) @ myapp ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-surefire-plugin:3.0.0-M1:test (default-test) @ myapp ---
[INFO] No tests to run.

Compared to running Maven locally, I can see:

[INFO] --- maven-compiler-plugin:3.8.1:testCompile (java-test-compile) @ myapp ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 65 source files to ...

So it would seem there is an issue with Heroku ignoring my test resources and code.

Could one any please share some references where i can find the real time interview questions for selenium experienced profile? [closed]

  • Could one any please share some references where i can find the real time interview questions for selenium experienced profile

Drop down list coming from database can't be handled using selenium

How to handle drop-down field data that comes from the database using selenium. A form contains 2 drop-down fields, one is having HTML data and it is handled perfectly. Data to the 2nd drop down comes as per the selection from the 1st which comes from the database. Need guides to complete the action.

How to test PHPUnit an authenticated user on Laravel with API middelware?

I'm triying to test a route and endpoint that requires an authtenticated user, but i'm getting some troubles. ¿How can I login an user in my test function?

  • My database model is not an Eloquent-Model.
  • I'm using phpUnit for testing

ENDPOINT:

Route::middleware('auth:api')->get('/myroute', 'MyController@MyFunction');

CONTROLLER (it works OK on frontend):

public function MyFunction()
{
  $loggedUser= auth()->user()->getAuthIdentifier();
  $results= $this->myUsecase->execute(new myCommand(new UserId($loggedUser)));
  return $this->response($this->serializer, $results);
}

TEST:

function testMyControllerCanSendResults()
{
    $response = $this->get('/api/myroute');
    $response->assertOk();
}

This test fails because the app nedds an authtenticated user to get his Identificator used in an Usecase.

I've tryed to make a custom Fake Factory for 'Usuario' model (but i've problems because my 'Usuario' model isn't a Eloquent Model.

What can I try? Thanks a lot!!!

Mock multiple TypeORM repositories in NestJS

I'm having trouble to mock multiple repositories from different modules in NestJS.

I'm using a UsersRepository from a UsersModule inside another module service (NotesService). The code is working fine, but I can't make the unit tests work.

I have the following error: Error: Nest can't resolve dependencies of the UserRepository (?). Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.

Minimal reproduction

// [users.module.ts]

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService],
})
export class UsersModule {}


// [users.service.ts]

@Injectable()
export class UsersService {
  constructor(@InjectRepository(User) private usersRepository: UsersRepository) {}
  ...
}


// [notes.module.ts]

@Module({
  imports: [
    TypeOrmModule.forFeature([Note, User]),
    UsersModule,
  ],
  controllers: [NotesController],
  providers: [NotesService],
})
export class NotesModule {
}

// [notes.service.ts]

@Injectable()
export class NotesService {
  constructor(
    @InjectRepository(Note) private notesRepository: NotesRepository,
    @InjectRepository(User) private usersRepository: UsersRepository,
  ) {}
  ...
}

Here is my unit test configuration:

// [notes.service.spec.ts]

beforeEach(async () => {
    const module = await Test.createTestingModule({
      imports: [UsersModule],
      providers: [
        NotesService,
        { provide: getRepositoryToken(Note), useFactory: repositoryMockFactory },
        { provide: getRepositoryToken(User), useFactory: repositoryMockFactory },
      ],
    }).compile();

    notesService = module.get<NotesService>(NotesService);
    notesRepositoryMock = module.get(getRepositoryToken(Note));
  });

The problem is I can't make a proper mock of the UsersRepository that comes from another module.

I tried importing TypeOrmModule directly inside the test, and everything I could but I can't make it work.

Thanks in advance!

Setting accessibility identifier doesn't work in react native

I want to set accessibility identifiers to my controls, mostly touchable controls for automation purpose. I am setting testID for iOS and accessibilityLabel for android but it isn't working. Not even in iOS.

Here is my code:

<TouchableHighlight
          btnTitle="Login"
          accessible={true}
          testID={"ButtonText"}
          accessibilityLabel={"ButtonTextDesc"}
        >
          <Text>Do something</Text>
</TouchableHighlight>

With this code, when I run app in simulator and check accessibility values in Accessibility Inspector, I don't see any identifier is setting up:

enter image description here

And when I do same thing for Text component only like:

<Text 
testID={testID} 
accessibilityLabel={accessibilityLabel} 
accessible={accessible}>
    Hello Test
</Text>

I get to see following in Accessibility Inspector app. enter image description here

Ideally I am expecting to see accessibilityIdentifier set for iOS components.

lundi 30 décembre 2019

Should Kotlin test classes be internal?

When you generate a test class for a given class in IntelliJ, say class Foo, it will generate a test class internal class FooTest. Why does it default to an internal class? What's the advantage of using internal classes for test classes?

The way I was generating test classes is: put cursor on the class name Foo, press Option/Alt+Enter, select "Create Test".

Testing rxjs pipe operator in constructor

I have class to handle the user/auth operations from firestore. The service works correctly but when I try to add test to the service if fails with the error TypeError: Cannot read property 'pipe' of undefined

This is my service

export class AuthService {
  user$: Observable<User>;

  constructor(private afAuth: AngularFireAuth, private afs: AngularFirestore) {
    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          return this.afs.doc<User>(`user/${user.uid}`).valueChanges();
        } else {
          return of(null);
        }
      })
    );
  }
}

and this is part my spec file for that class

describe('AuthService', () => {
  beforeEach(() =>
    TestBed.configureTestingModule({
      providers: [
        { provide: AngularFireAuth, useValue: FireAutStub },
        { provide: AngularFirestore, useValue: FirestoreStub }
      ],
      imports: [AngularFireModule, AngularFireAuthModule]
    })
  );

  it('AuthService should be created', () => {
    const service: AuthService = TestBed.get(AuthService);
    expect(service).toBeTruthy();
  });
});

any ideas of why the testing is throwing TypeError: Cannot read property 'pipe' of undefined or do you have any suggestions to test it better o make the service more "testable"?

How can I get choose the youtube video quality by using selenium in Python?

I'm having an issue to select the video quality resolution from the youtube video https://www.youtube.com/watch?v=JhdoY-ckzx4.

import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import threading


# This example will help us to open a video on youtube and skip the ads

options = webdriver.ChromeOptions() 

class ChromeTime(unittest.TestCase):

    def setUp(self):
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--incognito')
        chrome_options.add_argument("disable-popup-blocking")
        #chrome_options.add_argument('--headless')
        self.driver = webdriver.Chrome("/Users/hvaandres/Desktop/Dev_Projects/QA_Testing/Project_Video/chromedriver", options=chrome_options) #/usr/local/bin/chromedriver - Linux Machine
        self.driver.maximize_window()  

    def testing3(self):
        driver_chrome = self.driver

        driver_chrome.get("https://youtube.com")
        print("Opening Youtube")
        driver_chrome.find_element_by_name("search_query").send_keys("peter mckinnon")
        print("Looking for the youtuber")
        driver_chrome.find_element_by_id("search-icon-legacy").click()
        print("Finally, we found your youtuber!")
        time.sleep(5)
        driver_chrome.find_element_by_class_name("style-scope ytd-vertical-list-renderer").click()
        print("Trying to open thee video that you would like to watch")
        time.sleep(10)
        driver_chrome.find_element_by_class_name("ytp-ad-skip-button-container").click()
        print("You're skipping the ads")
        time.sleep(10)
        driver_chrome.find_element_by_class_name("ytp-popup ytp-settings-menu").click()
        time.sleep(10)

        print("Initial Page Title is : %s" %driver_chrome.title)
        windows_before  = driver_chrome.current_window_handle
        print("First Window Handle is : %s" %windows_before)


# Anything declared in tearDown will be executed for all test cases
    def tearDown(self):
        # Close the browser. 
        self.driver.close()

if __name__ == "__main__":
    unittest.main() 

I need to know what is the right CSS selector or element that I need to hit to choose the right element.

I tried several elements, but it seems that I'm not getting anywhere.

Caching Cypress on Sempahore

How is it possible to cache the Cypress binary on SempahoreCI?

Some instructions here suggest putting this in the Semaphore setup:

mkdir -p $SEMAPHORE_CACHE_DIR/Cypress
sudo ln -s $SEMAPHORE_CACHE_DIR/Cypress ~/.cache/Cypress

The setup job in Semaphore is run before every job.

Won't this recreate $SEMAPHORE_CACHE_DIR/Cypress directory for every Job?

Thus, not caching anything?

Is there a work-around for the Chrome error: "Require user gesture for beforeunload dialogs" during Cypress tests

https://www.chromestatus.com/feature/5082396709879808

Require user gesture for beforeunload dialogs

The beforeunload dialog will only be shown if the frame attempting to display it has received a user gesture or user interaction (or if any embedded frame has received such a gesture). (There will be no change to the dispatch of the beforeunload event, just a change to whether the dialog is shown.)

Here is the problem we're running into. In our single page app, business rules dictate that we alert the user if they click the browser back button.

Which is what this code does below in our app.js:

componentDidMount = () => {
    window.addEventListener('beforeunload', event => {
        event.returnValue = `Are you sure you want to leave?`;
    });
}

If the user navigates away on any page, the default alert box will pop up.

However in our Cypress tests we we have a beforeEach which goes back to the start of the app's flow before each test. This triggers the beforeunload event since we're leaving the page, but we don't see the alert, rather we get that chrome error:

Require user gesture for beforeunload dialogs

Anyone run into this before or have a clue on a work around?

Only thing I can think off at the moment is to remove the beforeEach but then we will need individual tests for each thing we want to test. Rather than just a few page test files...

Java library for command line Code Coverage calculation?

I am writing a Java program (using swing UI) that takes a java program (.java file with main function) and an excel file of large number of test cases as input.

It then uses Genetic Algorithm to return a limited size small subset of test cases that are best according to a criteria.

On of these criteria is Code Coverage.

I can easily write a fitness function that runs a command in cli and reads output. The only problem is that I need a tool that runs in command line and returns the value of code coverage (of bytecode or any other level). My fitness function will read this code coverage value and then try to maximize it for the entire subset.

Bottom line:- I need a tool to check code coverage of *.java files.

There are 2 classes in my case:-

TestingClass.java

import interest_calculator.CompoundInterest;

public class TestingClass {

    static CompoundInterest obj;
    public static final int ARGS_COUNT = 3;

    public static void main( String[] args ) {
        initializeClass();
        setValues( args );
        printResult();
    }

    private static void initializeClass() {
        obj = new CompoundInterest();
    }

    private static void setValues( String[] args ) {
        obj.principle = Double.parseDouble(args[0]);
        obj.rate = Double.parseDouble(args[1]);
        obj.time = Double.parseDouble(args[2]);
    }

    private static void printResult() {
        System.out.println( obj.calcCompoundInterest() );
    }

}

CompoundInterest.java (in a subfolder "interest_calculator"):-

package interest_calculator;

public class CompoundInterest {

    public double principle;
    public double rate;
    public double time;

    public double calcCompoundInterest() {
        double ci = principle * ( java.lang.Math.pow((1 + rate / 100), time) );
        ci = round( ci, 2 );
        return ci;
    }

    public double round(double value, int places) {
        if (places < 0) throw new IllegalArgumentException();

        long factor = (long) Math.pow(10, places);
        value = value * factor;
        long tmp = Math.round(value);
        return (double) tmp / factor;
    }

}

I need a tool that lets me call TestingClass from commandline using three commandline arguments and returns me code coverage of any kind (Literally Any Kind). I just need to demonstrate working of a Genetic Algorithm for code coverage.

Is there any suh tool. And how exactly do I use that tool for calculating code coverage with commandline arguments to my program.

The genetic algorithm is working for other criteria by the way. I am using Jenetics library for this purpose.

How to fix "java.lang.OutOfMemoryError: unable to create new native thread" on a Linux develoipment laptop

I am developing and running automated JVM Java performance tests on my laptop. Most of them use many thread polls extensively. I run into the following issue:

java.lang.OutOfMemoryError: unable to create new native thread

I am running on Ubuntu 16.04.6 LTS and Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode).

How can I develop and run my performance tests locally on my laptop before I submit them to being run in the performance test environment?

Cypress contains and cy.wait()

I've got some problem with Cypress and wait command: I am using similar to this code:

 const counter = cy.get('something')
        counter.contains('0') //OK
        const container = cy.xpath('something multiple').children()
        container.click({multiple:true})
        //cy.wait(200)
       counter.contains('3') //NOK

Only when I am using cy.wait() this code works. I've tried to use the internaltimeout for this code and it's not working. Only works when using cy.wait.

Validating the functionality of the application

I am trying to learn test script in python. I would like to write a test script to validate the functionality of an executable. The script should test the behaviour of the application, how the application handles error events and the specifications of the application are as follows,

  1. The application takes input data from a file that is specified as an argument and is called by executable.exe numbers.txt
  2. The numbers.txt file contains comma separated list of float number in each line
  3. The application computes and prints the average and standard deviation values for the numbers on each line in the input file(numbers.txt)

I came up till here

from validator_collection import validators, errors

# This funcion can be used to execute the application
# Inputs: executable, the executable file of the application
#         data, the input data file for the application
# Outputs: return code, standard output, and error output from the execution
def execute_application(executable, data):
    proc = subprocess.run(
            [executable, data],
            encoding="utf-8",
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
    return proc.returncode, proc.stdout, proc.stderr

# Call application
returncode, output, error = execute_application("executable.exe", "numbers.txt")

# The output of the program is 
#Output: data.txt
#Line 1 average 11.2333 standard deviation 9.34041
#Line 2 average 7.21667 standard deviation 7.29286

# started writing the test case
val = output.split(" ")
avg1, std1 = float(val[3]), float(val[6].strip('\nLine'))
avg2, std2 = float(val[9]), float(val[12].strip('\nLine'))
try:
    ret_avg1 = validators.float(avg1)
    ret_avg2 = validators.float(avg2)
    ret_std1 = validators.float(std1)
    ret_std2 = validators.float(std2)
except ValueError:
    print('Error')

print(ret_avg1, ret_avg2, ret_std1, ret_std2)
print("Output:", output)
print("Errors:", error)

Any pointers would be really helpful.

Comparing timestamp results from Postgres in Jest

I'm writing some tests in Jest for an API that's returning results from Postgres via the pg library. I post some data (via a faker'ed set of values, template1), and then test that what I get back is the same, allowing for an id value, and modified fields. The template1 data includes an approved property (SQL defn: approved timestamp with time zone), which is generated like so:

{
  approved: faker.date.past(),
  description: faker.lorem.paragraph(),
  groups: faker.lorem.paragraph(),
}

This test is something like this:

expect(response.body.rows).toStrictEqual([
    {
      ...template1,
      id: 1,
      modified: null,
    },
  ])

The issue is that the test is failing because the returned value of approved appears to be a string:

expect(received).toStrictEqual(expected) // deep equality

- Expected
+ Received

@@ -1,8 +1,8 @@
  Array [
    Object {
-     "approved": 2019-12-19T03:48:20.613Z,
+     "approved": "2019-12-19T03:48:20.613Z",
      "approved_by": "Percy_Hills@yahoo.com",

I've tried casting the template1.approved value just prior to the comparison to both a date, and to a string. Both approaches fail. What am I doing wrong, and how do I fix the issue?

Testlink installation failed within xammp in Windows

Today i tried to install Testlink on windows with xammp. path also set as

$g_repositoryPath = 'C:/xampp/htdocs/testlink/upload_area';
$tlCfg->log_path = 'C:/xampp/htdocs/testlink/logs';

But when i click on "Continue" button after checking the terms check box it gives

Parse error: syntax error, unexpected 'SCREEN' (T_STRING) in C:\xampp\htdocs\Testlink\config.inc.php on line 298

In the config.inc.php file code showing as below(mentioned part)

/**
 * @var string How to warning user when security weak points exists.
 *
 * 'SCREEN': messages will displayed on login screen, and tl desktop
 * 'FILE': a file with a list is created but users are not notified via GUI
 *         user will receive a message on screen. (default)
 * 'SILENT': same that FILE, but user will not receive message on screen.
 */
$tlCfg->config_check_warning_mode = 'FILE';

IS there any way to resolve this?

cy.click('div.wrapper') or cy.check('input[type=checkbox]', { force: true })?

Let's say there is some hidden checkbox wrapped with a styled div element:

<div class="wrapper beautiful-checkbox">
  <input type="checkbox" style="display: none">
</div>

In Cypress I want to test when user clicks on this element to choose this option. Which cy event is more suitable from the perspective of real user interaction:

  • cy.click('div.wrapper') - test user click event on wrapper element
  • cy.check('input[type=checkbox]', { force: true }) - test check event on the actual hidden checkbox using force: true option

dimanche 29 décembre 2019

Writing testable codes - Junit Test

Currently working on a project which requires me to write unit test for all the codes that I've implemented. I'm new to writing unit test and have recently picked up the knowledge on writing test cases using annotations like @MockBeans, @InjectMocks, @Spy to help me test out the particular method.

However, sometimes I do struggle with writing test cases which I couldn't mock and it ended up being an integration test. Below are some of the scenario I faced when writing out the test cases.

  1. Unit test for service layer ended up being a integration test as it interacts with the repo layer.

    • The repo layer returns a list of Tuple (javax.persistence.tuple) back to the service layer.
    • Mocked the repo layer, no issue on that.
    • Tried creating the list of Tuple that was supposed to be returned when the repo layer is called through Mockito.when(), however, I could not create the list of tuple as it does not have any setter method.
    • Ended up with a unit test that performing the actual query to the database to retrieve the values out which makes the unit test more like an integration test.
  2. A method which involved a factory method call in it. The factory classes are written as a static class and the returned concrete class are then autowired into spring context using the AutowireCapableBeanFactory

    • Since I could not mock a static factory, I just pass in the value into the factory and let it return the concrete class accordingly.
    • The concrete class returned by the factory could not be mocked.
    • The unit test would end up testing the concrete class as well.
  3. A method that instantiate a new class using new ConcreteClass() instead of @Autowired.

    • I think this is similar to the 2nd scenario I mentioned above.
    • @MockBeans will not work here since the concrete class is not created using @Autowired.

These are the scenario which I'm currently facing, and I spent a lot of time trying to figure out what is the correct way of writing my test cases or rather, how should I design my code in such a way that I could avoid all these issues? Appreciate your feedback and help on these scenarios to improve the way I write my unit test or code design, making it more testable!

How do I evaluate/test a .netstandard library

What's the best way of adhoc testing/coding When using .netstandard and/or .netcore?

I'm used to creating adhoc windows forms to test functionality in class libraries prior to integrating them into our code base. This approach enables me to single step the code, see what return values are, and most importantly dump output to a text box or grid. It's a useful way of digging into functionality. I also use this approach to create mini-apps for my own use, so I can just click the button, process some information and move on.

I'm now using a new library that targets .netstandard 2.1, and I find that my WinForms Framework app can't target that. If I move to Winforms Core then I'm forced to use the VS 2019 16.5 preview, which is ok for me but will be a barrier for our whole dev team. So what do I do? Use WPF forms for ad hoc testing, again ok for me but a pain for everyone else. I could use NUnit and single step but then I lose the output windows.

Testing an API endpoint with Lambda + API Gateway

I'm trying to create and test an API endpoint using AWS Lambda and API Gateway. I can test my function successfully using Lambda Test, but when I try to test my endpoint it gives:

{ "message": "Internal server error" }

This is my handler class:

package com.amazonaws.lambda.gandhi.conversion.api;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;

import com.amazonaws.lambda.gandhi.conversion.api.Response.AuthClientCredentialResponse;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

import com.amazonaws.lambda.gandhi.conversion.api.utils.ClientAuthPOJO;

public class AuthClientCredentialServiceHandler implements RequestHandler<ClientAuthPOJO, Object> {

    private AuthClientCredentialResponse authClientCredentialResponse;

    private static final SecureRandom RANDOM = new SecureRandom();
    public static int MAX_CLIENT_KEY = 10;
    public static int CLIENT_SECRET_LENGTH = 69;

    @Override
    public AuthClientCredentialResponse handleRequest(ClientAuthPOJO clientIdSecret, Context context) {
        String clientSecret;
        try {
            context.getLogger().log("Input: "
                    + clientIdSecret);
            String clientId = clientIdSecret.getClientId();
            clientSecret = generateClientSecretKey();
            Map<String, String> clientCredsMap = getClientCredentials();
            if (clientCredsMap.size() > MAX_CLIENT_KEY) {
                throw new RuntimeException(String.format("Max limit is %d, Please delete some keys", MAX_CLIENT_KEY));
            }
            clientCredsMap.forEach((k, v) -> {
                if (clientId.equals(k)) {
                    throw new RuntimeException("Client Already exists");
                }
            });
            storeClientCredentials(clientId, clientSecret);
            AuthClientCredentialResponse authClientCredentialResponse = AuthClientCredentialResponse.builder().success(
                    true).clientId(clientId).clientSecret(clientSecret).build();
            this.authClientCredentialResponse = authClientCredentialResponse;
        } catch (Exception e) {
            throw new RuntimeException(
                    "Failed to generate client secret: "
                            + e.getMessage());
        }
        return authClientCredentialResponse;
    }

    private String generateClientSecretKey() throws NoSuchAlgorithmException, InvalidKeySpecException {

        String clientSecret = RandomStringUtils.randomAlphanumeric(CLIENT_SECRET_LENGTH);
        System.out.printf("clientSecret: %s%n", clientSecret);
        return clientSecret;
    }

    private void storeClientCredentials(String clientId, String clientSecret) throws IOException {
        /*
         * TODO:
         * Some logic to store clientCredentials to a file or DB. Decide later.
         */
        System.out.println("temp ClientCredentials stored");
    }

    public Map<String, String> getClientCredentials() throws IOException {
        /*
         * TODO:
         * Some logic to fetch clientCredentials from file or DB. Decide later.
         */
        Map<String, String> clientCredMap = new HashMap<String, String>();
        clientCredMap.put("1", "secretKey1");
        clientCredMap.put("2", "secretKey2");
        clientCredMap.put("3", "secretKey3");
        clientCredMap.put("4", "secretKey4");
        return clientCredMap;
    }

}

My input class:

package com.amazonaws.lambda.gandhi.conversion.api.utils;

public class ClientAuthPOJO {
    String clientId;
    String clientSecret;

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public String getClientSecret() {
        return clientSecret;
    }

    public void setClientSecret(String clientSecret) {
        this.clientSecret = clientSecret;
    }

    public ClientAuthPOJO(String clientId, String clientSecret) {
        super();
        this.clientId = clientId;
        this.clientSecret = clientSecret;
    }

    public ClientAuthPOJO() {
    }

}

My test object in lambda: enter image description here

My test for endpoint in API Gateway: enter image description here

Can someone please help me figure out the problem in creating the function or API Gateway?

ModuleNotFoundError with package installed from github

I installed a package in my anaconda environment by entering the following line: pip3 install -e git+https://github.com/gauravmm/jupyter-testing.git#egg=jupyter-testing

I keep getting ModuleNotFoundError: No module named 'testing' on line: from testing.testing import test. I have no idea why this is happening, and believe it has something to do with the way my directory structure is set up.

My directory tree looks like this:

├── hw1_get_started.ipynb
├── requirements.txt
└── src
    └── jupyter-testing
        ├── jupyter_testing.egg-info
        │   ├── dependency_links.txt
        │   ├── PKG-INFO
        │   ├── SOURCES.txt
        │   └── top_level.txt
        ├── LICENSE
        ├── README.md
        ├── setup.py
        └── testing
            ├── __init__.py
            └── testing.py

I am trying to use this module : https://github.com/gauravmm/jupyter-testing.git#egg=jupyter-testing to do some testing in an online class.

I appreciate any help and explanation as to what I am doing wrong! :)

super considered super, dependency injection via inheritance in python

So, I have watched Raymond Hettinger's presentation super considered super and the ability to leverage dependency injection using super and multiple inheritance https://youtu.be/EiOglTERPEo

In one of his examples he is showing us how he'd mock a dependency by introducing a mock implementation of a base class and use this mock in a new childclass implementation in order to provide testability:

class Robot(object):
   def left(self):
      print("walking left")
   def right(self):
      print("walking right")

class MyRobot(Robot):
   def clean(self):
      super().left()
      super().right()

Now, in order to test MyRobot independently of the implementation of Robot, one should, according to his presentation, provide a mock implementation of Robot and use this in a new Testable class

class MockRobot(Robot):
   def left(self):
      print("mock left")
   def right(self):
      print("mock right")

class MyRobotTestable(MyRobot, MockRobot):
   pass

I understand how Method Resolution Order allows us to use the methods of MockRobot in the new testable class.

To be honest, I don't think of this as a good solution, since I am not testing my actual code on top of that I am introducing a new "class", yet only for the reason to make another class testable.

Coming from other OOP languages: Is there any reason, not to inject the dependency via the constructor?

i.e.:

class MyRobot(object):
   def __init__(robot):
      self.robot = robot

   def clean(self):
      self.robot.left()
      self.robot.right()

I don't need any additional class to provide testability (apart from the mock) and I can inject whatever implementation I want.

I consider this proper OOP following the Dependency Inversion rule.

Java conditional regex to check 24 hour time?‽

I am doing the following programming exercise: regex validation of 24 hours time. The statement is:

Write a regex to validate a 24 hours time string. See examples to figure out what you should check for:

Accepted: 01:00 - 1:00

Not accepted:

24:00

You should check for correct length and no spaces.

I would like to ask, why the following regular expression, matches 24:00

public class RegexValidation {
  public static boolean validateTime(String time) {
    System.out.println("time: "+time);
    return time.matches("(?:^[2])[0123]+:[0-5]+[0-9]|[0-9]+:[0-5]+[0-9]");
  }
}

Because I thought it was expressing: "If string starts with 2, then it should continue with [0-3] (one or more) : [0-5] one or more and [0-9]. Else it continues with [0-9] one or more : [0-5] one or more and [0-9]."

The tests are:

import org.junit.Test;
import static org.junit.Assert.*;

public class RegexValidationTest {

  @Test
  public void test1() {
    assertTrue(RegexValidation.validateTime("01:00"));
  }

  @Test
  public void test2() {
    assertTrue(RegexValidation.validateTime("1:00"));
  }

  @Test
  public void test3() {
    assertTrue(RegexValidation.validateTime("00:00"));
  }

  @Test
  public void test4() {
    assertFalse(RegexValidation.validateTime("13:1"));
  }

  @Test
  public void test5() {
    assertFalse(RegexValidation.validateTime("12:60"));
  }

  @Test
  public void test6() {
    assertFalse(RegexValidation.validateTime("24:00"));
  }
}

In addition I wrote the following solution, which passes the tests:

public class RegexValidation {
  public static boolean validateTime/*⌚*/(String time) {
    if(time.matches("[\\d]+:[\\d]{2}")){
      String[] times = time.split(":");
      int hours = Integer.parseInt(times[0]);
      int minutes = Integer.parseInt(times[1]);
      return hours < 24 && minutes < 60;
    }
    return false;
  }
}

I have also read:

Finally the question is, why in the first code the regex matches 24:00?‽

samedi 28 décembre 2019

Vue register all user activity - test tool?

In a couple of last months I was developing an Vue one page (almost, there's some 'route'-ing but not much) application. We are already in the end phase of alpha version and we will surely deliver it to our clients in a couple of weeks for first real live tests. But as far as I know, our end-users are just normal office people which doesn't have anything to do with programming. So if they will have some errors/troubles, they wont be able to communicate it in any helpful way. Instead they will rather say something like: 'I did this and that... I suppose... I'm not sure any more... and it stopped working'.

So I was thinking: maybe there's some tool which could register all user activities: mutations, events and so on (like in Vue Devtools) but maybe even more. Something that is able to, kind of 'play' it for us in a real time like a video (but still local in debug mode with the Vue Devtools on).

So it basically would have to work scrimba.com alike (sample: https://scrimba.com/p/pZ45Hz/c4Ny9U8). We don't need any voice and so on. It would be enough to build some 'trouble'-button which would open a dialog box, ask for comment and sent it to us with all infos we need (vuex and events record, browser infos etc.).

Of course, I was googling this, but you know how it works. If you don't know what you are looking for, the chances you will find it are quite slight. You can find a new way of using vuex or even cooking a new type of tomato soup, but to be efficient in this particular case, I decided that joining this great community will be way better :)

If this what I'm asking about is a total fantasy, I would be also happy about some tool which is collecting browser data gets a comment and screenshot and sends it to us (like Google 'Send feedback')

enter image description here

It's my first post here so if something should be done otherway I'm open for suggestions.

How to test my microservices before deploy to kubernetes?

I am creating a very small microservices environment for testing purpose. It looks as follows:

enter image description here

As you can see on the image, Istio is installed in the k8s cluster to use service mesh.

I wrote the BOO service, but do not know how to test the service, because it calls FOO and ZOO services.

I could mock FOO and ZOO services but when in the future the BOO services calls 10 further services, then it does make any sense then to mock all services.

What the best way to test my microservices before deploy to kubernetes?

JUNIT TEST FOR VOID METHOD ( output-input dependency )

I came up with a problem while trying to write a JUnit test for one specific method. I searched for possible solutions but many of them were not helpful as the output was not dependent on the input. Any help would be much appreciated.

My class method looks like this:

public static void method1() {
    Scanner input = new Scanner(System.in);
    String state = input.nextLine();
    if( /* condition dependent on state value */ ) {
        System.out.println("...");
    }
    else {
        System.out.println("..."+state+"...");
}

How to write a JUnit test for it, can Robot class somehow solve the problem?

Unable to install WebDriverAgent on real device using developer account

I am able to install WebDriverAgent using my personal apple id, But when I am using Developer account I am getting an error on running xcodebuild -project WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner -destination 'id=' test

my terminal is stuck at a point where it says "WebDriverAgentRunner-Runner[669:141632] Using singleton test manager " and later (~30-40 minutes)i get an error

Testing failed: WebDriverAgentRunner: testRunner encountered an error (Encountered a problem with the test runner after launch. (Underlying error: Lost connection to DTServiceHub))

Screenshot

Is MOCKING really useful apart from isolating dependent component testing?

So i am developing a security library for Wordpress. Basically building on top of a wordpress core component called Wordpress nonces
Everything seems to be fine.
Come back to the best practices, i have written a unit testing suite along with the library.
Since my library extends the wordpress noces api, wordpress is clearly a dependency in my library.

To achieve isolation when testing my library i used PHPUnit's mockBuilder so i can instantiate my dependency class instead of actually instantiating it because it calls an external dependency(wordpress nonce api).
Below is my Test class,

<?php
namespace nonces;

/**
 * TestWpNonce
 * Test suite for wp-clean-nonces library
 *
 * Wp-clean-nonces is A clean OOP implementation of the Wordpress Nonce library.
 * Copyright (C) 2019  Salim Said.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * For the complete terms of the GNU General Public License, please see this URL:
 * http://www.gnu.org/licenses/gpl-2.0.html

 * @category  NA
 * @package   NA
 * @author    Salim Said <saliimsaid@gmail.com>
 * @copyright 2019 Salim Said
 * @license   GPL-2.0+ <http://www.gnu.org/licenses/gpl-2.0.html>
 * @link      ****
 */

if(file_exists('../vendor/autoload.php'))
require_once '../vendor/autoload.php';

use PHPUnit\Framework\TestCase;
class TestWpNonce extends TestCase
{
    /**
     * This test will create a nonce for a url and verify if a correct
     * url is returned
     *
     * The method asserts for the result returned by createTokenUrl()
     * against a predefined expected return value containing a nonce
     * protected string url
     *
     * @return void
     */
    public function testCreateTokenUrl()
    {
        $wpNonce = $this->getMockBuilder(WPNonce::class)
            ->getMock();

        $wpNonce->expects($this->once())
            ->method('createTokenUrl')
            ->with($this->equalTo("inpsyde.com?action=publish_postid=2"))
            ->will($this->returnValue('inpsyde.com?action=publish_postid=2&token=297d58f6ae'));

        $this->assertEquals(
            "inpsyde.com?action=publish_postid=2&token=297d58f6ae",
            $wpNonce->createTokenUrl("inpsyde.com?action=publish_postid=2")
        );
    }
}

Look at the testCreateTokenUrl() method; it creates a mock for the WPNonce class, and calls the class method createTokenUrl() . This is where things starts to get interesting.

I am defining the input parameter like so with($this->equalTo("inpsyde.com?action=publish_postid=2")) and also explicitly expecting a return value as in ->will($this->returnValue('inpsyde.com?action=publish_postid=2&token=297d58f6ae'));

The assertEquals() method will check if the returned value is what i set in the preceding code.

This code helps me test the createTokenUrl() in isolation, it doesn't require wordpress(my library's dependency in this case). I can successfully get passing tests without having wordpress installed. That's fine but really what is the whole point of mocking project dependencies if the mock is actually a dummy test that is hard coded with arguments and return types ?

Is there a point of mocking that i am missing or i don't understand ?

Django GraphQL endpoint testing unable to use `variables` dictionary

How to use variables in django-graphql-jwt? I can use mutation in the iGraphQL with variables normally. Then it supposed to be working as well in my TestCase

from django.contrib.auth import get_user_model
from graphql_jwt.testcases import JSONWebTokenTestCase
from model_mommy import mommy

from multy_herr.commons.tests import JCMixin
from multy_herr.objections.models import Objection
from multy_herr.tweets.models import Tweet

User = get_user_model()


class UsersTest(JCMixin, JSONWebTokenTestCase):

    def setUp(self) -> None:
        super().setUp()
        mommy.make(Objection, _quantity=3)

    def test_authorized_user_hide_success(self):
        """
        Hide success
        :return:
        """
        tweet = Tweet.objects.first()

        query: str = '''
            mutation{
              objection(input: {
                tweet: $tweetId
                hidden: $hidden
              }){
                id
                hidden
                report
                tweet
                errors{
                  field
                  messages
                }
              }
            }
        '''
        variables = {
            'tweetId': str(tweet.id),
            'hidden': True,
        }
        self.client.authenticate(self.jc)
        res = self.client.execute(query, variables)

Here is res.error

res.errors
Out[3]: 
[graphql.error.base.GraphQLError('Variable "$tweetId" is not defined.'),
 graphql.error.base.GraphQLError('Variable "$hidden" is not defined.')]

Workaround:
I use .format() in Python to assign value to my variable, but I don't like that hackish way

Question:
Is it bug?

vendredi 27 décembre 2019

Writing tests with testing-library depends on implementation details of my UI library

I am using @testing-library to test my React project which uses Material-UI as it's main UI library. As @testing-library suggests, it's main philosophy is to test the application in the exact same way a user would use it. e.g click the button which says Submit or edit the input whose label is Username, etc... . And the testing-library gives me some helper methods like getByText, getByLabel, etc... .

My problem is that for some tests, forms' input tests for instance, I need to query an input's value or change it's current value. I need to getByLabel to query my label and go to parent component to query the input that is contained within. The library provides a closest DOM query helper, but is of no use in some situations, like the one I just described.

Writing my tests this way feels good, I mean writing tests as a user's point of view. But the problem is that I depend too much on implementation details of Material-UI. Maybe in next upgrade, the inputs and their corresponding label are not children of ancestor nodes, etc... .

Is there something I am doing wrong? Or is it the pitfall of the testing philosophy that @testing-library provides?

This is my packages stack:

{
    "@material-ui/core": "^4.7.1",
    "@material-ui/icons": "^4.5.1",
    "@material-ui/lab": "^4.0.0-alpha.34",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.0",
    "react": "^16.11.0",
    "react-dom": "^16.11.0",
    "react-scripts": "3.3.0-next.62"
}

react-testing-library's fireEvent.click not updating result of debug()

So I have created a simple ConnectFour game using React https://github.com/pavilion/ConnectFourTDD

I have created a Board and Cell components. The board is composed of a table of Cells.

The test renders a 4x4 Board and clicks the first element of the first column, so the outcome would be to get a X in the bottom of the first column:

+--------------------+--+--+--+
| Click happens here |  |  |  |
+--------------------+--+--+--+
|                    |  |  |  |
+--------------------+--+--+--+
|                    |  |  |  |
+--------------------+--+--+--+
| X                  |  |  |  |
+--------------------+--+--+--+

However, when I do debug() which basically prints the DOM tree, it doesn't show any "X". Here is the test: https://github.com/pavilion/ConnectFourTDD/blob/testing-library/packages/web/src/tests/App-test.tsx#L19

What am I doing wrong?

Why does Sinon FakeServer does not trigger with sinon >= 7.4.1?

At foodsharing.de we have some Sinon tests. Currently there is version <7.4.1 used but I wanted to upgrade it. According to the changelog there should be no issue, still: it won't work.

Here is the test: https://gitlab.com/foodsharing-dev/foodsharing/blob/41ae6e89dfa71903ee4d57b12fe34abd0a3f5913/client/src/script.test.js#L52

What fails is the mock browser on line 53:

mockBrowser
    .expects('goTo')
    .once()
    .withArgs(`/?page=msg&cid=${conversationId}`)

The error output:

1) script
   "after each" hook for "redirects to user chat page":
 ExpectationError: Expected goTo(/?page=msg&cid=10[, ...]) once (never called)

It seems that the ajax request is never executed, or at least there is no response? I am really not sure why does this happen.

script.chat(fsId)[1] calls conv.userChat(fsid)[2] which then calls ajax.req in the script.js[3].

[1] https://gitlab.com/foodsharing-dev/foodsharing/blob/41ae6e89dfa71903ee4d57b12fe34abd0a3f5913/client/src/script.js#L249

[2] https://gitlab.com/foodsharing-dev/foodsharing/blob/41ae6e89dfa71903ee4d57b12fe34abd0a3f5913/client/src/conv.js#L63

[3] https://gitlab.com/foodsharing-dev/foodsharing/blob/41ae6e89dfa71903ee4d57b12fe34abd0a3f5913/client/src/script.js#L376

It even calls the complete callback function with version >=7.4.1 but no fail and no success callback function is called...

Any ideas what is wrong? Did Sinon change anything back then?

Building a string pattern with two nested for loops makes the code too slow, with two separated, makes it to not pass the tests‽

I am doing the following programming exercise: Complete The Pattern #4. The statement is:

Task:

You have to write a function pattern which creates the following pattern upto n number of rows. If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.

Examples:

pattern(4):

1234 234 34 4

pattern(6):

123456 23456 3456 456 56 6

Note: There are no blank spaces

Hint: Use \n in string to jump to next line

I have tried the following naive solution:

public class Pattern {

    public static String pattern/*🅿️*/(int n) {
    String result = "";
    for(int i = 1; i <= n; i++){
      for(int j = i; j <= n; j++){
        result += j;
      }      
      result += "\n";
    }
    return result.strip();
    }
}

Which runs out of time (the execution time is longer than 16000 ms) for input of three digits like: 496, 254, 529...

Then, I tried to simplify it, removing the nested loop and just iterating a first time to put all the numbers range, and then iterating a second time to append the rest of the pattern:

public class Pattern {

    public static String pattern/*🅿️*/(int n) {
    System.out.println("n: "+n);
    String result = "";
    for(int i = 1; i <= n; i++){
      result += i;
    }
    System.out.println("result after first loop: "+result);
    for(int i = 1; i < n; i++){
      result += "\n"+result.substring(i,n);
    }
    System.out.println("result after second loop:\n"+result);
    return result.strip();
    }
}

I have been debugging and I have found that this second solution outputs correct only when n is a one digit number. For example when n is 7:

n: 7
result after first loop: 1234567
result after second loop:
1234567
234567
34567
4567
567
67
7

However, when n is a two digits number:

n: 11
result after first loop: 1234567891011
result after second loop:
1234567891011
2345678910
345678910
45678910
5678910
678910
78910
8910
910
10
0

And the output should be:

Expected...
<...567891011
2345678910[11
34567891011
4567891011
567891011
67891011
7891011
891011
91011
1011
11]>

But was...
expected:<...567891011
2345678910[
345678910
45678910
5678910
678910
78910
8910
910
10
0]>

Being the test cases (extracted from the exercise):

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class PatternTest {
    @Test
    public void pattern() throws Exception {
        assertEquals( Pattern.pattern( 1 ), "1" );
        assertEquals( Pattern.pattern( 2 ), "12\n2" );
        assertEquals( Pattern.pattern( 5 ), "12345\n2345\n345\n45\n5" );
    assertEquals( Pattern.pattern( 7 ), "1234567\n234567\n34567\n4567\n567\n67\n7" );
    assertEquals( Pattern.pattern( 11 ), "1234567891011\n234567891011\n34567891011\n4567891011\n567891011\n67891011\n7891011\n891011\n91011\n1011\n11" );
        assertEquals( Pattern.pattern( 0 ), "" );
        assertEquals( Pattern.pattern( -25 ), "" );
        assertEquals( Pattern.pattern( -59 ), "" );
    }
}

I understand the bug is with result.substring(i,n) because of we are assuming that each number will count as 1 in the oop (will only have one digit), which is incorrect, it could have more digits...

How could we improve this code?‽

I have also read:

@WebMvcTest keeps attempting to start ApplicationContext

Isn't the whole point of using @WebMvcTest as opposed to @SpringBootTest to avoid the running of the ApplicationContext? I'm not sure why my test keeps attempting to start it.

MY TEST

class BoardControllerIntegrationTest {

    @MockBean
    BoardServiceImpl boardService;

    @Autowired
    MockMvc mockMvc;

    Board validBoard;

    @BeforeEach
    void setUp() {
        validBoard = Board.builder()
                .setBoardName("Test Board 1")
                .setBoardId(UUID.randomUUID())
                .setRetroType("madSadGlad")
                .setDateCreated(LocalDate.now())
                .build();
    }

    @AfterEach
    void tearDown() {
        reset(boardService);
    }

    @Test
    void testGetBoardByUUID() throws Exception {
        Optional<Board> boardOptional = Optional.of(validBoard);
        given(boardService.findById(any())).willReturn(boardOptional);

        mockMvc.perform(get("/board/" + validBoard.getBoardUUID()))
                .andExpect(status().isOk());
    }


}

THE EXCEPTION

java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:95)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:79)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:54)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)

Can anyone shed any light on this?

Skipped test is not logged as Skipped in ExtentReport4

I got 2 tests: addNewVideo and deleteRecentVideo where the second one depends on first one. After first fails, second gets ignored and it's not running. After opening my Extent Report, it looks like this: enter image description here

I'm expecting to have 2 tests - 1 failed, 1 skipped, but it's not showing properly on the report.

ExtentListener.class


import com.aventstack.extentreports.*;
import com.aventstack.extentreports.markuputils.*;
import org.testng.*;
import java.util.*;
import static constants.FileResources.REPORT_DIR;

public class ExtentListener implements ITestListener {

    private static Date d = new Date();
    private static String fileName = String.format("%s%s%s%s", d.toString().replaceAll("[: ]", "_"), "_", System.getenv("env"), ".html");
    private static ExtentReports extent = ExtentManager.createInstance(REPORT_DIR + fileName);
    public static ThreadLocal<ExtentTest> testReport = new ThreadLocal<>();

    @Override
    public void onTestStart(ITestResult result) {
        ExtentTest test = extent.createTest(result.getTestClass().getName() + "." + result.getMethod().getMethodName());
        test.assignCategory(result.getTestClass().getName());
        testReport.set(test);
    }

    @Override
    public void onTestSuccess(ITestResult result) {
        String methodName = result.getMethod().getMethodName();
        String logText = methodName + " PASSED";
        Markup m = MarkupHelper.createLabel(logText, ExtentColor.GREEN);
        testReport.get().pass(m);
    }

    @Override
    public void onTestFailure(ITestResult result) {
        String methodName = result.getMethod().getMethodName();
        String excepionMessage = Arrays.toString(result.getThrowable().getStackTrace());
        testReport.get().fail("<details>" + "<summary>" + "<b>" + "<font color=" + "red>" + "Exception occured: Expand to check details"
                + "</font>" + "</b >" + "</summary>" + excepionMessage.replaceAll(",", "<br>") + "</details>" + " \n");
        String failureLog = methodName + " FAILED";
        Markup m = MarkupHelper.createLabel(failureLog, ExtentColor.RED);
        testReport.get().log(Status.FAIL, m);
    }

    @Override
    public void onTestSkipped(ITestResult result) {
        String methodName = result.getMethod().getMethodName();
        String logText = "<b>" + methodName + " SKIPPED" + "</b>";
        Markup m = MarkupHelper.createLabel(logText, ExtentColor.ORANGE);
        testReport.get().skip(m);
    }

    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {

    }

    @Override
    public void onStart(ITestContext context) {

    }

    @Override
    public void onFinish(ITestContext context) {
        if (extent != null) {
            extent.flush();
        }
    }
}

I've tried implementing IInvokedMethodListener but no success. Is there any way to show skipped tests properly on ExtentReport4?

JUnit tests not running in order

I am using JUnit 5 to test DynamoDB, and I have a set up method annotated with @BeforeAll where I insert 3 items in the database, and one annotated with @AfterAll to delete the items in the database after all the test have run.

@Test
@Order(1)
public void addNewCar() {
    repository.save(new Car("d"));

    assertThat(repository.count()).isEqualTo(4);
}

I am inserting a new item first, and then I delete one item:

@Test
@Order(2)
public void deleteCar() {
    repository.deleteById("a");

    assertThat(repository.count()).isEqualTo(2);
}

However, the first test is failing (the count is 3 instead of 4) because the car that is deleted in test number 2 is already removed in test number 1.

I am able to solve it by running by annotating the setup and clean database methods with @BeforeEach and AfterEach, but I am curious why my item is already deleted in test 1?

Vietnamese language input method

I'm from Vietnam, We setup a kiwi server, it runs ok. But my problem is I can not write in Vietnam language when we create test case, test plan or write describe. It shows: " 500 Internal error"

Could you pls show me how to fix it. Thanks.

How could we refactor two related logics which are part of the same algorithm, into two separate methods‽

I am doing the following programming exercise: Traffic Lights - one car. Its statement is:

Overview

A character string represents a city road.

Cars travel on the road obeying the traffic lights..

Legend:

. = Road
C = Car
G = GREEN traffic light
O = ORANGE traffic light
R = RED traffic light

Something like this: C...R............G......

Rules Simulation

At each iteration:

the lights change, according to the traffic light rules... then
the car moves, obeying the car rules

Traffic Light Rules

Traffic lights change colour as follows:

GREEN for 5 time units... then
ORANGE for 1 time unit... then
RED for 5 time units....
... and repeat the cycle

Car Rules

Cars travel left to right on the road, moving 1 character position per time unit

Cars can move freely until they come to a traffic light. Then:
    if the light is GREEN they can move forward (temporarily occupying the same cell as the light)
    if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through)
    if the light is RED the car must stop until the light turns GREEN again

Kata Task

Given the initial state of the road, return the states for all iterations of the simiulation. Input

road = the road array
n = how many time units to simulate (n >= 0)

Output

An array containing the road states at every iteration (including the initial state)
    Note: If a car occupies the same position as a traffic light then show only the car

Notes

There is only one car
For the initial road state
    the car is always at the first character position
    traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles
There are no reaction delays - when the lights change the car drivers will react immediately!
If the car goes off the end of the road it just disappears from view
There will always be some road between adjacent traffic lights

Example

Run simulation for 10 time units

Input

road = "C...R............G......"
n = 10

Result

    [   "C...R............G......", // 0 initial state as passed  
    ".C..R............G......", // 1
   "..C.R............G......", // 2  
    "...CR............G......", // 3
   "...CR............G......", // 4  
    "....C............O......", // 5 show the car, not the light  
    "....GC...........R......", // 6
   "....G.C..........R......", // 7  
    "....G..C.........R......", // 8
   "....G...C........R......", // 9  
    "....O....C.......R......"  // 10 ]

First I have written the following code:

public class Dinglemouse {
  public static String[] trafficLights/*🚦🚦*/(String road, int n) {
    System.out.println("\n\nroad: "+road);
    System.out.println("\nn: "+n);
    String[] items = road.split("");
    int semaphoreTimeUnits = 0;
    boolean carHasMovedThisIteration = false;
    String hiddenSemaphore = "";
    String[] iterations = new String[n+1]; iterations[0] = road;

    for(int i = 0; i < n; i++, semaphoreTimeUnits++){
      //System.out.println("i: "+i);
      for(int j = 0; j < items.length - 2; j++){
        //System.out.println("j: "+j);
        //System.out.println("semaphoreTimeUnits: "+semaphoreTimeUnits);
        if(items[j].equals("C") && !carHasMovedThisIteration && !items[j+1].equals("R")){
          if(hiddenSemaphore.equals("")){
            items[j] = ".";
          }else{
            if(hiddenSemaphore.equals("O")){
              if(road.charAt(j) == 'R'){
                items[j] = "G";
              }else if(road.charAt(j) == 'G'){
                items[j] = "R";
              }else{
                items[j] = hiddenSemaphore;
              }
            }
            hiddenSemaphore = "";
          }
          if(!items[j+1].equals(".")){
            hiddenSemaphore = items[j+1];
          }
        items[j+1] = "C";
        carHasMovedThisIteration = true;
        }
        if(items[j+2].equals("R") && road.charAt(j+2) == 'R' && semaphoreTimeUnits >= 4
        || items[j+2].equals("G") && road.charAt(j+2) == 'G' && semaphoreTimeUnits >= 4){
          items[j+2] = "O";    
        }
        if(items[j+2].equals("O") && semaphoreTimeUnits >= 5){
          if(road.charAt(j+2) == 'R'){
            items[j+2] = "G";    
          }else if(road.charAt(j+2) == 'G'){
            items[j+2] = "R";  
          }
        }
        if((items[j+2].equals("G") || items[j+2].equals("R")) && semaphoreTimeUnits >= 10){
          items[j+2] = String.valueOf(road.charAt(j+2));    
          semaphoreTimeUnits = 0;
        }
        //System.out.println("items: "+String.join("", items));
      }
      iterations[i+1] = String.join("", items);
      System.out.println("items: "+String.join("", items));
      carHasMovedThisIteration = false;
    }
    return iterations;
  }
}

And the test (extracted from the exercise)

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;


public class ExampleTests {

  private static void doTest(String initial, String[] expected, int n) {
    String got[] = Dinglemouse.trafficLights(initial, n);
    assertEquals("Result array length", expected.length, got.length);

    int errIdx = -1;
    for (int i = 0; i < got.length; i++) {
      if (!expected[i].equals(got[i])) { errIdx = i; break; }
    }

    System.out.println("Expected:");
    for (int i = 0; i < expected.length; i++) {
      System.out.println(String.format("%03d %s", i, Common.display(expected[i])));
    }

    if (errIdx >= 0) {
      System.out.println("\nYour result:");
      for (int i = 0; i < got.length; i++) {
        System.out.println(String.format("%03d %s", i, Common.display(got[i])));
      }
      fail(String.format("A difference was detected at index %d", errIdx));
    }
  }

  @Test
  public void example() {
    int n = 10;
    String sim[] = {
      "C...R............G......",  // 0
      ".C..R............G......",  // 1
      "..C.R............G......",  // 2
      "...CR............G......",  // 3
      "...CR............G......",  // 4
      "....C............O......",  // 5
      "....GC...........R......",  // 6
      "....G.C..........R......",  // 7
      "....G..C.........R......",  // 8
      "....G...C........R......",  // 9
      "....O....C.......R......"   // 10
    };
    doTest(sim[0], sim, n);
  }

}

Expected is:

Expected:
000 C...R............G......
001 .C..R............G......
002 ..C.R............G......
003 ...CR............G......
004 ...CR............G......
005 ....C............O......
006 ....GC...........R......
007 ....G.C..........R......
008 ....G..C.........R......
009 ....G...C........R......
010 ....O....C.......R......

The code output is:

Your result:

000 C...R............G......
001 .C..R............G......
002 ..C.R............G......
003 ...CR............G......
004 ...CR............G......
005 ....C............O......
006 ....GC...........R......
007 ....G.C..........R......
008 ....G..C.........R......
009 ....G...C........R......
010 ....G....C.......R......

So then as you will notice:

A difference was detected at index 10

Because of it expects an O instead of the G, at index 10.

1) How do we achieve that the car when is at an orange traffic light, the next 4 iterations it shows a green light, instead of the next 5 ones, as is being printed now.

2) How could we refactor, simplify the code, to separate car movement logic, and traffic ligths logic.

I have tried to extract car movement logic as:

public class Dinglemouse {
  public static String[] trafficLights/*🚦🚦*/(String road, int n) {
    System.out.println("\n\nroad: "+road);
    System.out.println("\nn: "+n);
    String[] items = road.split("");
    int semaphoreTimeUnits = 0;
    boolean carHasMovedThisIteration = false;
    String hiddenSemaphore = "";
    String[] iterations = new String[n+1]; iterations[0] = road;

    for(int i = 0; i < n; i++, semaphoreTimeUnits++){
      //System.out.println("i: "+i);
      for(int j = 0; j < items.length - 2; j++){
        //System.out.println("j: "+j);
        //System.out.println("semaphoreTimeUnits: "+semaphoreTimeUnits);

        simulateCarMovement(j, items, carHasMovedThisIteration, hiddenSemaphore, road);

        if(items[j+2].equals("R") && road.charAt(j+2) == 'R' && semaphoreTimeUnits >= 4
        || items[j+2].equals("G") && road.charAt(j+2) == 'G' && semaphoreTimeUnits >= 4){
          items[j+2] = "O";    
        }
        if(items[j+2].equals("O") && semaphoreTimeUnits >= 5){
          if(road.charAt(j+2) == 'R'){
            items[j+2] = "G";    
          }else if(road.charAt(j+2) == 'G'){
            items[j+2] = "R";  
          }
        }
        if((items[j+2].equals("G") || items[j+2].equals("R")) && semaphoreTimeUnits >= 10){
          items[j+2] = String.valueOf(road.charAt(j+2));    
          semaphoreTimeUnits = 0;
        }
        //System.out.println("items: "+String.join("", items));
      }
      iterations[i+1] = String.join("", items);
      System.out.println("items: "+String.join("", items));
      carHasMovedThisIteration = false;
    }
    return iterations;
  }


  static void simulateCarMovement(int j, String[] items, boolean carHasMovedThisIteration, String hiddenSemaphore, String road){
    if(items[j].equals("C") && !carHasMovedThisIteration && !items[j+1].equals("R")){
      if(hiddenSemaphore.equals("")){
        items[j] = ".";
      }else{
        if(hiddenSemaphore.equals("O")){
          if(road.charAt(j) == 'R'){
            items[j] = "G";
          }else if(road.charAt(j) == 'G'){
            items[j] = "R";
          }else{
            items[j] = hiddenSemaphore;
          }
        }
        hiddenSemaphore = "";
      }
      if(!items[j+1].equals(".")){
        hiddenSemaphore = items[j+1];
      }
    items[j+1] = "C";
    carHasMovedThisIteration = true;
    }
  }
}

However I think we have some difficulties with the variables being passed into the simulateCarMovement method, because of they are not being returned. So then the output for this refactored code would be:

Expected:
000 C...R............G......
001 .C..R............G......
002 ..C.R............G......
003 ...CR............G......
004 ...CR............G......
005 ....C............O......
006 ....GC...........R......
007 ....G.C..........R......
008 ....G..C.........R......
009 ....G...C........R......
010 ....O....C.......R......

Your result:
000 C...R............G......
001 ...CR............G......
002 ...CR............G......
003 ...CR............G......
004 ...CR............G......
005 ......................C.
006 ......................C.
007 ......................C.
008 ......................C.
009 ......................C.
010 ......................C.

A difference was detected at index 1

I have also read:

How could we refactor two related logics which are part of the same algorithm, into two separate methods‽

What is difference between api testing and database testing?

What is difference between api testing and database testing? Because internally api also do the operation on database. Guys Please answer.

jeudi 26 décembre 2019

ModuleNotFoundError: No module named 'numpy.testing.decorators'

I'm trying to import numpy, getting this error,

ModuleNotFoundError: No module named 'numpy.testing.decorators'

Can someone help/guide me to overcome this?

Is there a way to pass a new request in KarateDSL during retry? Thank you

My feature is something like this:

Scenario:  Searching Value
* def Search = generateRandomNumberFive(111,999)
* call read('classpath:services/common.feature')
Given url domain + '/localhost/mysearch?query=' + Search
And headers scenarioHeaders
And retry until myRecord != $response.suggestions[0].ID == 8
When method get
Then status 200
* def myRecord = $response.suggestions[?(@.ID==8)]

I would like iSearch value to be regenerated on succeeding retries. Thanks for your help.

How to test async code with Jest without passing it as a callback?

Will be grateful if someone could clarify to me how test the async code from inquirer plugin for CLI app.

The module exports updateView function, which calls async inquirer.prompt inside.

const inquirer = require("inquirer");

const getAnswer = async (request) => {
    const answer = await inquirer.prompt(request);
    return answer;
}

Want to test with Jest that async code works, however all the Jest examples I have seen show ways to test async code only if I pass async function as a parameter.

So my function will have to be refactored to that:

getAnswers.js

const getAnswer = async (request, callback) => {
    const answer = await callback(request);
    return answer;
}

main.js

const inquirer = require("inquirer");
const getAnswers = require("./getAnswers");

const main = async () => {
    const request = "abc";
    const result = async getAnswers(request, inquirer.prompt);
...
}

And then test file will look like that:

test.js

const getAnswers = require("./getAnswers");

  test("async code works", async () => {
    //Arrange
    const mock = async () => {
      return "Correct Answer";
    };

    //Act
    const result = async getAnswers("abc", mock);

    //Assert
    expect(result).toEqual("Correct Answer";);
  });

Will be very grateful if someone could suggest if there is a way of testing async function without passing it as a callback?

And if the approach itself is correct.

Thank you very much,

Katya

Yields "TypeError: Cannot read property 'xxxx' of undefined" after running jest with Vue

I'm trying to make a test using jest with Vue.

the details below.

Problem:

  • Can't mount using shallowMount option.

Situation:

  1. Run the test after mounting the component using shallowMount option that provides in Vue-test-utils.
  2. Throw error "Cannot read property 'XXXX' of undefined

This is my test code.

import myComponent from '@/~';
import Vuex from 'vuex';
import Vuelidate from 'vuelidate';
import { shallowMount, createLocalVue } from '@vue/test-utils';

const localVue = createLocalVue();
localVue.use(Vuex);
localVue.use(Vuelidate);

describe('myComponent~', () => {
  let store;

  beforeEach(() => {
    store = new Vuex.Store({
      modules: {
        user: {
          namespaced: true,
          getters: {
            profile: () => {
              const profile = { name: 'blahblah' };
              return profile;
            },
          },
        },
      },
    });
  });

  describe('profile.name is "blahblah"', () => {
    it('return something~', () => {
      const wrapper = await shallowMount(myComponent, {
        localVue,
        store,
        mocks: {
          $api: {
            options: {
              testMethod() {
                return new Promise((resolve, reject) => {
                  resolve('test');
                });
              },
            },
          },
          $i18n: {
            t() {
              return {
                EN: 'EN',
                KO: 'KO',
                JP: 'JA',
                SC: 'zh-CN',
                TC: 'tw-CN',
              };
            },
          },
        },
      });
      expect(wrapper.find('.profile').text()).toBe('blahblah');
    });

I think the problem is that property isn't set as a specified value or an empty value like an array or object.

But how I set properly the properties in my logic.

For example,

when the error yields "Cannot read property 'images' of undefined",

I add to a wrapper in the relevant method like this.

exampleMethod() {
 this.something = this.something.map(item => {
  if (item.detailContent.images) { // <-- the added wrapper is here
   ~~~logic~~~~
  }
 })
}

But the undefined properties are so many, I also think this way is not proper.

How I do solve this problem?

Is there a way to test smart watch apps on a real device (not an emulator) online?

I mean a service like pCloudy (https://www.pcloudy.com/), that includes smart watches as well. I couldn't find any...

Which is a professional way to write about the possible errors or exceptions that a program can trigger?

I have not worked in software professionally, only at a hobby/studient level and I would like to know how professionals handle in their documentation about a program's possible errors and exceptions that might be triggered during execution.

I would like to know if there are any set of rules so any programmer who has the duty to fix an error or exception reads this text and knows were it happened and why.

I'm looking for an universal way to do it. No matter what computer language you are working with.

Python - Unit Testing Patch

I'm having some issues getting @patch to work with my unit tests, after patching an import the mock doesn't seem to be picked up and the 'regular' class is used instead

The class and method I'm trying to test are shown below (simplified for sake of the question)

from sila2lib.sila_server import SiLA2Server
# ... snip ...

class DeviceService:

def __init__(self, central_message_queue: asyncio.Queue, config: Config):

    self.central_message_queue: asyncio.Queue = central_message_queue
    self.logger = logging.getLogger('GWLogger')

    # ...... snip ......

async def start_device_server(self, tag_config: dict) -> asyncio.Queue:

    # Message queue used for passing messages to running device features (instrument readings)
    name = tag_config["Name"]
    uuid = tag_config["UUID"]
    cfg = tag_config["FeatureConfig"]

    # SiLA Server Setup [This is what I want to mock]
    self.device_server = SiLA2Server(name=name,
                                     description="Provides Device specific functions",
                                     server_uuid=uuid,
                                     port=self.device_server_port,
                                     ip=self.device_server_address,
                                     simulation_mode=False,
                                     key_file=None,
                                     cert_file=None)

    # ........ snip .......

And an example test - all I want to do is swap out the SilaServer with a MagicMock so I can verify a method has been called with the correct params

import asynctest, asyncio
from tests.util.MockConfig import build_mock_config
from unittest.mock import patch, MagicMock
from services.device.DeviceService import DeviceService

class DeviceServiceTests(asynctest.TestCase):

@patch("services.device.DeviceService.SiLA2Server")
async def test_device_info_load(self, mock_sila_server_class):

    mock_sila_server_instance = MagicMock()
    mock_sila_server_class.return_value = mock_sila_server_instance
    message_queue = asyncio.Queue()
    device_service = DeviceService(message_queue, build_mock_config())
    device_service.logger = MagicMock()

    await device_service.start_device_server(empty_tag_config)

    # Test feature has been set
    mock_sila_server_instance.add_feature.assert_called_with(data_path='',
                                                             feature_id='DeviceInfo',
                                                             servicer=None)

    # Check that server was started
    mock_sila_server_instance.run.assert_called_with(block=False)

And project structure

Project Structure

The test runs and fails as the mock isn't being used and I get an assertion exception as you'd expect, adding a breakpoint and examining the device_service is using the actual class

Var inspect

I feel it's something really obvious but I just can't see it, I have other similar tests that work fine with @patch decorators but there doesn't seem to be any difference in how its applied in those tests and this one

Any help is really appreciated

Jest: Testing imported module to call another function that returns a function that is then tested

This one seems like a bit of a brain teaser but lets give it a shot! So I am testing a function that calls a function from a module that then returns a function that I then need to test. I know this is a bit convoluted. I was thinking of splitting it apart but the testing all parts from one actually makes a lot of sense in this case because of its helper function nature. So let's begin:

Spec:

import { functionToTest } from './moduleToTest';

describe('helper function' , () => {
    it('should call the function_Returning_Object_WithFunction().THE_REAL_FUNCTION_TO_TEST with the value that I have in this spec sheet', () => {
        expect(function_Returning_Object_WithFunction().THE_REAL_FUNCTION_TO_TEST) // expectation
    });
});

moduleToTest:

import { function_Returning_Object_WithFunction } from './module_for_this'

export const functionToTest = (value) => {
    if (function_Returning_Object_WithFunction().THE_REAL_FUNCTION_TO_TEST) {
        function_Returning_Object_WithFunction().THE_REAL_FUNCTION_TO_TEST('string', {
            someKey: someValueToTestWasPassed
        }
    }
}

So what happens:

  1. Helper function called a function that returns an object
  2. That object has a function that needs to be called with a specific value passed down

I am not exactly sure where to begin. I have tried stubbing the first function that is called and returning an object that has the function acting as a spy but that doesn't work I get a "function_Returning_Object_WithFunction() is a read-only function" error.

Please let me know if I can clarify I know this can be difficult with so many layers.

How to verify relational record inserted or not from c# list

This is testing approach task,

I have List<Customers>, let's assume customer list have 10 records and all customer have 3 orders, ( please note in real requirement, there can be n records and it may be x orders).

public class Customers
{
  public int CustomerId {get;set;}
  public int CustomerTableXYZUniqueId {get;set;}
  public List<orders> orders{ get; set; }
}

public class Orders
{
  public int OrderId {get;set;}
  public int CustomerId {get;set;}
  public int OrderTableXYZUniqueId {get;set;}
  public List<orders> orders{ get; set; }
}

so total 30 rows will be enter across 2 tables. parent Table : customer child Table : order

Now in C#, I need to execute a SQL query, which will guarantee me that all 30 rows records have been entered in.

What query should I write in SQL to verify that all records are inserted in 2 tables?

parent Table : customer
child Table : orders

Maybe something like this, but not sure:

select * from customer as poh  join
orders as poL customer.customerId  = orders.customerId 
where customer.CustomerTableXYZUniqueId in ( "172772,18282881,28282818")
and orders.orderTableXYZUniqueId in ('37371', "182882");

do you have suggestion please?

Edit1 :

What i am trying to do is, i'm sending List to some POST API call, when API call returning me success, i want to run some kind of sql script via c# which will make sure that records are entered with exact fields value.

here in this example, i have chosen fields property are Customer/OderXYZUniqueId,

So i will read Customer/OderXYZUniqueId values and include in SQL query and see if records are inserted or not.

Allure Create Screenshot - Selenium

I'm having trouble taking screenshots with allure. I have configured my interface in which in case of failure test I call the function whose task is to create a screenshot in the report. However, this does not work. Screenshot are not created.

Below is my interface:

package Test;

import Test.resources.Base;
import io.qameta.allure.Allure;
import io.qameta.allure.Attachment;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

import java.io.ByteArrayInputStream;
import java.io.IOException;

public class ListenersT extends Base implements ITestListener {
    Base b = new Base();


    public void onFinish(ITestContext arg0) {
        // TODO Auto-generated method stub

    }


    public void onStart(ITestContext arg0) {
        // TODO Auto-generated method stub

    }

    public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
        // TODO Auto-generated method stub

    }



    public void onTestFailure(ITestResult result) {
        // TODO Auto-generated method stub
        //screenshot

        try {
            b.getScreenshot(result.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }

        Object testClass = result.getInstance();
        WebDriver driver = ((Base) testClass).getDriver();
        if(driver instanceof  WebDriver) {
            takeScreenshot(driver);
        }
    }

    @Attachment(value = "Page screenshot", type ="image/png")
    public byte[] takeScreenshot(WebDriver driver) {
        byte[] screenshotAs = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
        return screenshotAs;
    }


    public void onTestSkipped(ITestResult arg0) {
        // TODO Auto-generated method stub

    }

    public void onTestStart(ITestResult arg0) {
        // TODO Auto-generated method stub

    }

    public void onTestSuccess(ITestResult arg0) {
        // TODO Auto-generated method stub

    }


}

And here is my base class form which extend my interface:

package Test.resources;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Listeners;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class Base {

    public static WebDriver driver;


    public WebDriver initializeDriver() throws IOException {

        Properties prop = new Properties();
        FileInputStream fis = new FileInputStream(System.getProperty("user.dir") + "\\src\\main\\java\\Test\\resources\\data.properties");
        prop.load(fis);

        Properties propBuykers = new Properties();
        FileInputStream fisBuykers = new FileInputStream(System.getProperty("user.dir") + "\\src\\main\\java\\Test\\resources\\data.propertiesBuykers");
        propBuykers.load(fisBuykers);

        String browserName;

        if(System.getProperty("browser") == null) {
            browserName = "chrome";
        }
        else {
            browserName = System.getProperty("browser");
        }


        //String browserName = prop.getProperty("browser");

        if(browserName.contains("chrome")) {
            System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\ChromeDriver\\chromedriver2.exe");
            ChromeOptions options = new ChromeOptions();


            if(browserName.contains("headless")) {
                options.addArguments("headless");
            }
            driver = new ChromeDriver(options);
        }
        else if(browserName.equals("firefox")) {
            System.setProperty("webdriver.gecko.driver", "C:\\Program Files (x86)\\GeckoDriver\\geckodriver.exe");
            driver = new FirefoxDriver();
        }
        else if(browserName.equals("edge")) {
            System.setProperty("webdriver.edge.driver", "C:\\Program Files (x86)\\MicrosoftWebDriver\\msedgedriver.exe");
            driver = new EdgeDriver();
        }

        else if (browserName.equals("remoteBrowser")) {
            DesiredCapabilities caps = DesiredCapabilities.chrome();
            caps.setCapability("platform", "Windows 10");
            caps.setCapability("version", "66.0");

            RemoteWebDriver driver = new RemoteWebDriver(new URL("g42664-b435-4a95-9b68-f43b51a43134@ondemand.eu-central-1.saucelabs.com:443/wd/hub"), caps);
            driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
            driver.manage().window().maximize();
            return driver;
        }

        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();

        return driver;
    }

    public void getScreenshot(String result) throws IOException {
        File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(src, new File("C://s//"+result+"screenshot.png"));
    }

    public WebDriver getDriver() {
        return driver;
    }
}

Please help me what I am doing wrong.