dimanche 28 février 2021

How to poll for latest product build from jenkins

I have multiconfiguration automated testsuite project working in automated fashion periodically, but the it runs with same product build everytime. I want it to run only when there is new build on a given link.

Problem: Polling the scm is one option but, My SCM is set to git which contains my testing automation suite, and I need to poll svn to check for new builds, and I don't know if or how to setup multiple scm in single project

How can I achieve this ??

How to force springboot return Json response with global settings

Here are problems. They who are testing my application told me that when they trying to directly input the url into address to query a GET url by chrome. My api will always return a XML formatted response like this. enter image description here

But all the response should be formatted in JSON string ! XML is unacceptable !

I tried to analyze the source code and found request sending by chrome directly will bear attributes like this:

accept= text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3;q=0.9
content-type=null

while any other application will send request with:

accept= */* (or accept = application/json)
content-type = application/json

In this case , springboot will then response XML to the request send by chrome because of the missing content-type and specified accept properties.

There is a way to fix this case by excluding jackson for XML in pom. But I don't think it is a graceful way.

I think there are ways more graceful to fix this problem. Help me please. Thanks a lot!

Android Testing Activity Started by Handler.postDelayed

I'm new to using the Roboelectric testing framework and the issue that I am having is not being able to build an activity. I used the same exact test in every class and they worked as expected, except for the CallingActivity that relies on being called by Handler.postDelayed which I believe is the problem.

This is the code that will create the CallingActivity:

btnCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Handler().postDelayed(new Runnable()
                {
                    @Override
                    public void run() {
                        Intent intent = new Intent(FakePhoneCallMenuActivity.this, CallingActivity.class);
                        intent.putExtra("callerName", nameEntryBox.getText().toString());
                        intent.putExtra("callerPhoneNum", phoneEntryBox.getText().toString());
                        intent.putExtra("callerVoice", voice);
                        startActivity(intent);
                    }
                }, timeToStart);
            }
        });

This is test for the CallingActivity that is having issues working:

@RunWith(RobolectricTestRunner.class)
@Config(sdk = {Build.VERSION_CODES.O_MR1})
public class CallingTest {
    private CallingActivity activity;

    @Before
    public void setUp() throws Exception {
        activity = Robolectric.buildActivity(CallingActivity.class)
                .create()
                .start()
                .resume()
                .get();
    }

    @Test
    public void acceptCallButtonClickShouldStartNewActivity() throws Exception {
        ShadowActivity shadowActivity = shadowOf(activity);
        ImageButton button = (ImageButton) shadowActivity.getContentView().findViewById(R.id.btnAcceptCall);
        button.callOnClick();
        Intent startedIntent = shadowActivity.getNextStartedActivity();
        ShadowIntent shadowIntent = shadowOf(startedIntent);
        assertEquals(FakePhoneCallMenuActivity.class, shadowIntent.getIntentClass());
    }
}

The issue that I am recieving after trying to run this test is:

java.lang.Exception: Main looper has queued unexecuted runnables.

Help with this would be greatly appreciated!

Thanks

No views in hierarchy found matching: Child at position 0 in parent Child at position 0 in parent view.getId

I created an instrumental test with android studio, using Express Record Test.

Flow:
-> Starts in the Activity_splash_screen class.
-> Then the LoginActivity.java screen goes to the screen.
-> After the login screen goes to another actitivity (ValuesPeternActivity.java) that asks for the DDI, the phone and a user ID.
Ending the flow in HomeActivity.java

1 ° The test fills in the login and password fields; (success)
2 ° Click on the next heading to a new screen; (success)
3 ° An error occurs because it stops in the txtDDI field, which is the first field on the second screen. (error)

If I insist on executing repeatedly, sometimes the test passes, sometimes not even the first screen test passes. I believe it characterizes a lack of synchrony between the express and the thread.

How to sync?
I found out about it but I was unable to implement it. see link -> IdlingRegistry and Espresso will wait for the resource

I saw a video in which the guy was doing this test and didn't need any of that. It must be because of androidx, it can only!

Mistake of error:

Started running tests


        androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching: Child at position 0 in parent Child at position 0 in parent view.getId() is <2131296889/br.com.cellsgroupleader:id/txtDDI>

        View Hierarchy:
        +>DecorView{id=-1, visibility=VISIBLE, width=1366, height=406, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params={(0,0)(wrapxwrap) gr=CENTER sim={adjust=pan} ty=APPLICATION fmt=TRANSLUCENT wanim=0x10302f9
          fl=DIM_BEHIND FULLSCREEN ALT_FOCUSABLE_IM SPLIT_TOUCH HARDWARE_ACCELERATED}, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1} |
        +----->Space{id=16909413, res-name=titleDividerNoCustom, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@d7e62e0, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0} 
        |
        +---->FrameLayout{id=16908813, res-name=contentPanel, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@5ed645e, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1} 
        +------->Space{id=16909395, res-name=textSpacerNoTitle, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@550d2d1, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0} 
        |
        +------->AppCompatTextView{id=16908299, res-name=message, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@24ba136, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=, input-type=0, ime-target=false, has-links=false} 
        |
        +------->Space{id=16909394, res-name=textSpacerNoButtons, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@b164837, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0} 
        |
        +---->FrameLayout{id=16908820, res-name=customPanel, visibility=VISIBLE, width=1254, height=294, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@83ecb0d, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1} 
        |
        +----->FrameLayout{id=16908331, res-name=custom, visibility=VISIBLE, width=1254, height=294, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@3fd30d3, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}
        |
        +---->ScrollView{id=16908766, res-name=buttonPanel, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@16fe74b, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1} 
        |
        +----->ButtonBarLayout{id=-1, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@d8ccbd4, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=4} 
        |
        +------>AppCompatButton{id=16908315, res-name=button3, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@505917d, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=, input-type=0, ime-target=false, has-links=false} 
        |
        +------>Space{id=16909328, res-name=spacer, visibility=INVISIBLE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@9613872, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0} 
        |
        +------>AppCompatButton{id=16908314, res-name=button2, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@7c3f4c3, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=, input-type=0, ime-target=false, has-links=false} 
        |
        +------>AppCompatButton{id=16908313, res-name=button1, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=true, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@4d4d140, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=, input-type=0, ime-target=false, has-links=false} 
        |
        +-->ViewStub{id=16908682, res-name=action_mode_bar_stub, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, layout-params=android.widget.FrameLayout$LayoutParams@ddec879, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0} 
        |
            at dalvik.system.VMStack.getThreadStackTrace(Native Method)
            at java.lang.Thread.getStackTrace(Thread.java:1538)
            at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:12)
            at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:7)
            at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:8)
            at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:11)
            at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:4)
            at br.com.cellsgroupleader.Activity_splash_screenTest.activity_splash_screenTest(Activity_splash_screenTest.java:111)

        Tests ran to completion.

Activity_splash_screen_Test generated by the Express Record Test
Here I had to put editText.check (matches (withText (endsWith ("joseb@gmail.com")))).
The endWidth help to take only what is necessary, because I was making a mistake here.

package br.com.cellsgroupleader;

        import android.content.*;
        import android.view.*;

        import androidx.test.espresso.*;
        import androidx.test.filters.*;
        import androidx.test.platform.app.*;
        import androidx.test.rule.*;
        import androidx.test.runner.*;

        import org.hamcrest.Description;
        import org.hamcrest.*;
        import org.junit.*;
        import org.junit.runner.*;

        import static androidx.test.espresso.Espresso.*;
        import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
        import static androidx.test.espresso.action.ViewActions.*;
        import static androidx.test.espresso.assertion.ViewAssertions.*;
        import static androidx.test.espresso.matcher.ViewMatchers.*;
        import static org.hamcrest.Matchers.*;
        import static org.junit.Assert.*;

        @LargeTest
        @RunWith( AndroidJUnit4.class )
        public class Activity_splash_screenTest{
           
           @Rule
           public ActivityTestRule < Activity_splash_screen > mActivityTestRule = new ActivityTestRule <>( Activity_splash_screen.class );
          
           @Test
           public void useAppContext( ){
              // Context of the app under test.
              Context appContext = InstrumentationRegistry.getInstrumentation( ).getTargetContext( );
              assertEquals( "br.com.cellsgroupleader" , appContext.getPackageName( ) );
           }
           
           @Test
           public void activity_splash_screenTest( ){
              ViewInteraction textInputEditText = onView(
                 childAtPosition(
                    childAtPosition(
                       withId(R.id.email) ,
                       0 ) ,
                    0 ) );
                    textInputEditText.perform( scrollTo( ) , click( ) );
              
              ViewInteraction textInputEditText2 = onView(
                 childAtPosition(
                    childAtPosition(
                       withId( R.id.email ) ,
                       0 ) ,
                    0 ) );
              textInputEditText2.perform( scrollTo( ) , replaceText( "joseb@gmail.com" ) , closeSoftKeyboard( ) );
              
              ViewInteraction textInputEditText3 = onView(
                 allOf( withText( "joseb@gmail.com" ) ,
                    childAtPosition(
                       childAtPosition(
                          withId( R.id.email ) ,
                          0 ) ,
                       0 ) ) );
              textInputEditText3.perform( pressImeActionButton( ) );
              
              ViewInteraction textInputEditText4 = onView(
                 childAtPosition(
                    childAtPosition(
                       withId( R.id.password ) ,
                       0 ) ,
                    0 ) );
              textInputEditText4.perform( scrollTo( ) , replaceText( "123456" ) , closeSoftKeyboard( ) );
              
              ViewInteraction textInputEditText5 = onView(
                 allOf( withText( "123456" ) ,
                    childAtPosition(
                       childAtPosition(
                          withId( R.id.password ) ,
                          0 ) ,
                       0 ) ) );
              textInputEditText5.perform( pressImeActionButton( ) );
              
              ViewInteraction editText = onView(
                 allOf( withText( "joseb@gmail.com" ) ,
                    withParent( withParent( withId( R.id.email ) ) ) ,
                    isDisplayed( ) ) );
              editText.check( matches( withText(endsWith("joseb@gmail.com")) ) );
              
              ViewInteraction editText2 = onView(
                 allOf( withText( "123456" ) ,
                    withParent( withParent( withId( R.id.password ) ) ) ,
                    isDisplayed( ) ) );
              editText2.check( matches( withText(endsWith("123456")) ) );
              
              ViewInteraction appCompatButton = onView(
                 allOf( withId( R.id.btnEnviarLogin ) , withText( "Entrar" ) ,
                    childAtPosition(
                       childAtPosition(
                          withClassName( is( "android.widget.LinearLayout" ) ) ,
                          4 ) ,
                       1 ) ) );
              appCompatButton.perform( scrollTo( ) , click( ) );
           
              ViewInteraction textInputEditText6 = onView(
                 childAtPosition(
                    childAtPosition(
                       withId( R.id.txtDDI ) ,
                       0 ) ,
                    0 ) );
              textInputEditText6.perform( scrollTo( ) , replaceText( "+55" ) , closeSoftKeyboard( ) );
           
              ViewInteraction textInputEditText7 = onView(
                 allOf( withText( "+55" ) ,
                    childAtPosition(
                       childAtPosition(
                          withId( R.id.txtDDI ) ,
                          0 ) ,
                       0 ) ) );
              textInputEditText7.perform( pressImeActionButton( ) );
           
              ViewInteraction textInputEditText14 = onView(
                 allOf( withText( "(48)96456-5896" ) ,
                    childAtPosition(
                       childAtPosition(
                          withId( R.id.txtfone ) ,
                          0 ) ,
                       0 ) ,
                    isDisplayed( ) ) );
              textInputEditText14.perform( closeSoftKeyboard( ) );
           
              ViewInteraction textInputEditText15 = onView(
                 allOf( withText( "(48)96456-5896" ) ,
                    childAtPosition(
                       childAtPosition(
                          withId( R.id.txtfone ) ,
                          0 ) ,
                       0 ) ) );
              textInputEditText15.perform( pressImeActionButton( ) );
           
              ViewInteraction textInputEditText16 = onView(
                 childAtPosition(
                    childAtPosition(
                       withId( R.id.txtcodigoID ) ,
                       0 ) ,
                    0 ) );
              textInputEditText16.perform( scrollTo( ) , longClick( ) );
           
              ViewInteraction linearLayout = onView(
                 allOf( withContentDescription( "Colar" ) ,
                    childAtPosition(
                       childAtPosition(
                          withClassName( is( "android.widget.RelativeLayout" ) ) ,
                          1 ) ,
                       0 ) ,
                    isDisplayed( ) ) );
              linearLayout.perform( click( ) );
           
              ViewInteraction textInputEditText17 = onView(
                 childAtPosition(
                    childAtPosition(
                       withId( R.id.txtcodigoID ) ,
                       0 ) ,
                    0 ) );
              textInputEditText17.perform( scrollTo( ) , replaceText( "-MU7CLJOxn3s8iG7l9MS" ) , closeSoftKeyboard( ) );
           
              ViewInteraction textInputEditText18 = onView(
                 allOf( withText( "-MU7CLJOxn3s8iG7l9MS" ) ,
                    childAtPosition(
                       childAtPosition(
                          withId( R.id.txtcodigoID ) ,
                          0 ) ,
                       0 ) ) );
              textInputEditText18.perform( pressImeActionButton( ) );
           
              ViewInteraction editText3 = onView(
                 allOf( withText( "+55" ) ,
                    withParent( withParent( withId( R.id.txtDDI ) ) ) ,
                    isDisplayed( ) ) );
              editText3.check( matches( withText( "+55" ) ) );
           
              ViewInteraction editText4 = onView(
                 allOf( withText( "(48)96456-5896" ) ,
                    withParent( withParent( withId( R.id.txtfone ) ) ) ,
                    isDisplayed( ) ) );
              editText4.check( matches( withText( "(48)96456-5896" ) ) );
           
              ViewInteraction editText5 = onView(
                 allOf( withText( "-MU7CLJOxn3s8iG7l9MS" ) ,
                    withParent( withParent( withId( R.id.txtcodigoID ) ) ) ,
                    isDisplayed( ) ) );
              editText5.check( matches( withText( "-MU7CLJOxn3s8iG7l9MS" ) ) );
           
              ViewInteraction appCompatButton2 = onView(
                 allOf( withId( R.id.txtAvancar ) , withText( "Avançar" ) ,
                    childAtPosition(
                       childAtPosition(
                          withClassName( is( "android.widget.ScrollView" ) ) ,
                          0 ) ,
                       6 ) ) );
              appCompatButton2.perform( scrollTo( ) , click( ) );
           }
           
           
           
           private static Matcher < View > childAtPosition(
              final Matcher < View > parentMatcher , final int position ){
              
              return new TypeSafeMatcher < View >( ){
                 @Override
                 public void describeTo( Description description ){
                    description.appendText( "Child at position " + position + " in parent " );
                    parentMatcher.describeTo( description );
                 }
                 
                 @Override
                 public boolean matchesSafely( View view ){
                    ViewParent parent = view.getParent( );
                    return parent instanceof ViewGroup && parentMatcher.matches( parent )
                       && view.equals( ( ( ViewGroup ) parent ).getChildAt( position ) );
                 }
              };
           }
        }

./gradle

plugins {
            id 'com.android.application'
            id 'com.google.gms.google-services'
        }

        android {
            signingConfigs {
                release {
                    storeFile file('/home/fsp/Área de Trabalho/PRIVATE KEYS ANDROID/KEYS_ANDROID')
                    storePassword ''
                    keyAlias ''
                    keyPassword ''
                }
                debug {
                    storeFile file('/home/fsp/Área de Trabalho/PRIVATE KEYS ANDROID/KEYS_ANDROID')
                    storePassword ''
                    keyAlias ''
                    keyPassword ''
                }
            }
            compileSdkVersion 30
            buildToolsVersion "30.0.3"

            defaultConfig {
                applicationId "br.com.cellsgroupleader"
                minSdkVersion 23
                targetSdkVersion 30
                versionCode 1
                versionName "1.0.1"
                testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
                signingConfig signingConfigs.release
            }
            testOptions {
                unitTests.returnDefaultValues = true
            }
            useLibrary 'android.test.runner'
            useLibrary 'android.test.base'
            useLibrary 'android.test.mock'

            compileOptions {
                sourceCompatibility JavaVersion.VERSION_1_8
                targetCompatibility JavaVersion.VERSION_1_8
            }
            ndkVersion '21.3.6528147'
            buildTypes {
                release {
                    signingConfig signingConfigs.release
                }
                debug {
                    signingConfig signingConfigs.debug
                }
            }
        }

        dependencies {
            implementation fileTree(dir: 'libs', include: ['*.jar'])
            implementation 'androidx.appcompat:appcompat:1.2.0'
            implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
            implementation 'androidx.recyclerview:recyclerview:1.1.0'
            implementation 'androidx.preference:preference:1.1.1'

            //noinspection GradleDependency
            implementation 'androidx.navigation:navigation-fragment:2.3.2'

            //noinspection GradleDependency
            implementation 'androidx.navigation:navigation-ui:2.3.2'
            implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
            implementation 'androidx.cardview:cardview:1.0.0'
            implementation 'androidx.drawerlayout:drawerlayout:1.1.1'
            implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0'

            //noinspection GradleDependency
            implementation 'com.google.android.material:material:1.2.0-alpha02'
            implementation 'com.google.firebase:firebase-auth:20.0.2'
            implementation 'com.google.android.gms:play-services-auth:19.0.0'
            implementation 'androidx.test.espresso:espresso-intents:3.4.0-alpha04'
            androidTestImplementation 'androidx.test:rules:1.3.0'

            //noinspection GradleDependency
            implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

            // Required -- JUnit 4 framework
            testImplementation 'junit:junit:4.13.2'
            // Optional -- Robolectric environment
            testImplementation 'androidx.test:core:1.3.0'
            // Optional -- Mockito framework
            testImplementation 'org.mockito:mockito-core:1.10.19'

            // Core library
            androidTestImplementation 'androidx.test:core:1.3.0'

            // AndroidJUnitRunner and JUnit Rules
            androidTestImplementation 'androidx.test:runner:1.3.0'
            androidTestImplementation 'androidx.test:rules:1.3.0'

            // Assertions
            androidTestImplementation 'androidx.test.ext:junit:1.1.2'
            androidTestImplementation 'androidx.test.ext:truth:1.3.0'
            androidTestImplementation 'com.google.truth:truth:1.0'

            // Espresso dependencies
            androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
            androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.3.0'
            androidTestImplementation 'androidx.test.espresso:espresso-intents:3.3.0'
            androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.3.0'
            androidTestImplementation 'androidx.test.espresso:espresso-web:3.3.0'
            androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.3.0'

            //firebase
            implementation 'com.google.firebase:firebase-functions:19.2.0'
            implementation 'com.google.firebase:firebase-storage:19.2.1'
            implementation platform('com.google.firebase:firebase-bom:26.3.0')
            implementation 'com.google.firebase:firebase-analytics'
            implementation 'com.google.firebase:firebase-database:19.6.0'
            implementation 'com.google.firebase:firebase-auth:20.0.2'
            implementation 'com.github.prolificinteractive:material-calendarview:1.4.3'

            //glide
            implementation 'com.github.bumptech.glide:glide:4.8.0'
            implementation 'androidx.legacy:legacy-support-v4:1.0.0'
            //noinspection GradleDependency
            implementation 'androidx.navigation:navigation-dynamic-features-fragment:2.3.2'
            annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
        }

How to import class to test using ES6 modules

Hello I have a folder structure that looks like this:

  • Folder
    • index.js
    • someClass.js
    • index.html
  • Tests
    • someclass.test.js

I've exported this someClass using export default, imported it using import statement to index.js and after I open index.html, everything works, however I can't import this class to someClass.test.js file and after I run jest I get this error

 **SyntaxError: Cannot use import statement outside a module**

I've also changed type property in package.json file to be module. How to solve this issue?

What is widget testing?

I just started with testing in flutter i am writing unit tests for my business logic. I am also familiar with mocking dependencies, however widget testing is quite overwhelming? In Widget testing what are we actually doing? Can someone answer this with a simple analogy

Puppeteer with Firefox - on some sites page.goto throws "TimeoutError: Navigation timeout of 30000 ms exceeded"

The following code prints "success" to console

 puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch({
    product: "firefox",
    headless: false
  });
  const page = await browser.newPage();
  await page.goto("https://google.com/");
  console.log('success');
  await browser.close();
})();

Changed the site from 'google' to 'twitter'. The following code results in TimeoutError: Navigation timeout of 30000 ms exceeded

const puppeteer = require("puppeteer");
(async () => {
  const browser = await puppeteer.launch({
    product: "firefox",
    headless: false
  });
  const page = await browser.newPage();
  await page.goto("https://twitter.com/");
  console.log('success');
  await browser.close();
})();

Validate nested response body rest assured

I know that there is a lot of information regarding validations in rest assure but unfortunately I am not able to find exactly the solution to my issue.

I am training to validate the response of the following JSON:

{
"A":[
  {
     "B":[
        {
           "C":"c",
           "D":"d"
        }
     ],
     "E":[
        {
           "F":[
              {
                 "G":"g1"   
              }
           ]
        },
        {
           "F":[
              {
                 "G":"g2"
              }
           ],
        },
        {
           "F":[]
        }
     ]
  }
],
"H": "h"
}

with the following code:

 response.body("A.E.F.G", hasItems(expectedValues.get(G).toArray(new String[0])))

expectedValues.get(G) return a list of g1 and g2.

the ERROR that I get is:

JSON path A.E.F.G doesn't match.
Expected: an array containing ["g1", "g2"]
Actual: [[[g1], [g2], []]]

How can I get that done?

how to write a python program that can tell whether the numbers entered can form a triangle or not?

i was writing the following code:

def form_triangle(num1,num2,num3):

    success="Triangle can be formed"
    failure="Triangle can't be formed"

    if(num1 < num2 + num3):
        if(num2 < num1 + num3):
            if(num3 < num1 + num2):
                return success
        
    else:
        return failure


num1=3
num2=3
num3=5
result = form_triangle(num1, num2, num3)  
print(result)

but the problem is this code is unable to pass all the test cases. for instance, if num1, num2, num3 have values 1, 2, 3 respectively, then the expected output should be N/A but my output is None. so, what changes should i have to made in my code to have the expected output.

selenium - Selecting dates where the date information of the element is in a different div to the selectable element

Here is the webpage I am trying to write an automated test for:

https://aw1.automationintesting.online/#/

In my test, (not shown), i pass in a month and year and the test clicks through the calendar until the label of the calendar matches the month and year i have passed in.

When i get to the required month year, I want to be able to select a date range whereby i pass in the dates that i want. Here is what i have:

Actions action = new Actions(DriverFactory.getInstance().getDriver());

action.moveToElement(landingPage.date(from))
    .clickAndHold(landingPage.date(from))
    .moveToElement(landingPage.date(to))
    .release(landingPage.date(to))
    .build()
    .perform();

landingPage.date is a selector whereby i find the element by LinkText and pass in the date.

I can see it doing "something" but its not actually selecting the date i pass in.

When I hardcode the selector to a full xpath or cssselector for the the class "rbc-day-bg", it is able to select the date range.

The selector holding the date information and the selector for actually interacting with the calendar are in 2 separate divs.

What selector should i be using to be able to pass in dates to make a selection without hardcoding the selector ?

I hope this makes sense

Thank you in advance

How can ng test cause dependency resolving errors?

While testing a component with ng test I ran into a cascade of errors similar to this

Error: ./node_modules/protractor/built/runner.js
Module not found: Error: Can't resolve 'child_process' in '/<path-to-project>/node_modules/protractor/built'
resolve 'child_process' in '/<path-to-project>/node_modules/protractor/built'
Parsed request is a module using description file: /<path-of-project>/node_modules/protractor/package.json (relative path: ./built)
Field 'browser' doesn't contain a valid alias configuration
resolve as module
<continued with other modules e.g. sauceLabs, selenium-webdriver>

The test is only testing if a part of the component is defined.

const card = element(By.tag('mat-card-content'))
expect(card).toBeDefined()

How do I test custom error messages with the help of CUnit?

Hello everyone I am new to Cunit.My question is below the code so you may skip it if you want to. I made a small function that adds two positive integers and returns the result and if any of the integers is less than or equal to zero then it writes to stderr an error message.

/*This file is dummy.c*/
#include "dummy.h"

int add(int a,int b)
{
   if(a<=0||b<=0)
   {
       fprintf(stderr,"Error in arguments");
       exit(EXIT_FAILURE);
   }
   else
       return a+b;
}

This is dummy.h

#include<stdio.h>
#include<stdlib.h>

int add(int a,int b)

This is a part of my CUnit test code. Filename is testdummy.c

/*Necessary files have been included*/
void addtest()
{
    CU_ASSERT_EQUAL(add(3,5),8);
    CU_ASSERT_EQUAL(add(1,6),7);
    /*What should I add here*/
}

What should I add in the section specified so that my code is also tested for error messages?

samedi 27 février 2021

Simulating keyboard events with JavaScript

How to simulate typing of some text in a contenteditable element? I need to simulate everything as a user will events will do for test purposes. I can fire an event with:

node.dispatchEvent(new KeyboardEvent('keydown', {key: 'A'}))
node.dispatchEvent(new KeyboardEvent('keyup', {key: 'A'}))

But it will not print A. So I have to use API:

node.innerHTML += 'A'

But the cursor will be in a different place, so I need to create a range.

let r = document.createRange()
r.selectNodeContents(editor)
r.collapse(false)
let s = window.getSelection()!
s.removeAllRanges()
s.addRange(r)

What about simulating arrows? How to simulate arrow up? Maybe there is some library to do this?

java.lang.NullPointerException in Selenium Webdriver test

I am trying to better understand Selenium Webdriver, and writing some code based on instructions from a short training I did last year. The idea is to write a test that will check if Google browser opens up and searches for a word. The code below does not work as I get the java.lang.NullPointerException for WebElement in my InteliJ. Not sure what is wrong, I would appreciate some advice:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class startOverStartGoogle {
WebDriver driver;

@Before
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", 
"C:\\Users\\karol\\OneDrive\\Pulpit\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://google.co.uk");
driver.manage().window().maximize();
System.out.println(driver.getTitle());
driver.navigate().refresh();
System.out.println(driver.getTitle());

}
@Test
public void googleSearch() {
**WebElement** typeYourSearch = driver.findElement(By.cssSelector("a4bIc"));
typeYourSearch.sendKeys("Scotland");
**List<WebElement>** searchList = driver.findElements(By.cssSelector("q"));
assertThat(searchList.size()).isGreaterThanOrEqualTo(10);
}
@After
public void endTest(){driver.close();}
}

Testing a function with for loop with Robot Framework

I have a python function contains a for loop This function returns a bunch of True and False.

I would like to test this function using RobotFramework and count the number of times for True as passed and False as failed in the report.html

what could be the clean way to do that?

Email verification with selenium

This is the method I'm using for get the verification code which received to the mail.I wanted to get only the verification code from this.so that ,I have used line preceding the code begins with. But I received the result as null

public String getVerificationCode() throws Exception {
Message email = getMessagesBySubject("ABCD | Email Verification", true, 5)[0];
BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));

String line;    
while ((line = reader.readLine()) != null) {
  if(line.startsWith("Please use below")) {
    return reader.readLine();
  }
}
return null;
}

Related email template I'm using,

Email Verification

We've noticed that you have updated your email address.

Please use below code to verify your email address.

2955

I would like to know why I received the return as null from this method and the ways to resolve this matter.

Change the payload in a test

I am testing my login endpoint in Insomnia Designer with the integrated test tool.

A successful login test looks like this with the selected login request:

const response = await insomnia.send();
const body = JSON.parse(response.data);

expect(response.status).to.equal(200);
expect(body).to.have.property("token");

Now I want to change the test with invalid credentials in order to check for a response.status 401.

How can I change this in Insomnia Designer programmatically?

Unit test DAO classes with JUnit using a Connection Pool

Hi everyone i'm new here and i need your help to unit test with junit a DAO class with a connection pool. This is the ConPool:

public class ConPool {

private static DataSource datasource;

/**
 * {@return} Connection
 * {@throws} SQLException
 *     Ritorna la connessione al db.
 */

public static Connection getConnection() throws SQLException {
if (datasource == null) {
  PoolProperties p = new PoolProperties();
  p.setUrl("jdbc:mysql://localhost:3306/GameLand?serverTimezone="
          + TimeZone.getDefault().getID());
  p.setDriverClassName("com.mysql.cj.jdbc.Driver");
  p.setUsername("root");
  p.setPassword("basedidati");
  p.setMaxActive(100);
  p.setInitialSize(10);
  p.setMinIdle(10);
  p.setRemoveAbandonedTimeout(60);
  p.setRemoveAbandoned(true);
  datasource = new DataSource();
  datasource.setPoolProperties(p);
}
  return datasource.getConnection();
 }
}

and this is the DAO class that i want to test:

public class OrdineDAO {
/**
 * {@return} ArrayList of Ordine.
 */

public synchronized ArrayList<Ordine> doRetrieveAll() {

String query = "SELECT * FROM ordine";
ArrayList<Ordine> result = new ArrayList<Ordine>();

try (Connection conn = ConPool.getConnection()) {

  PreparedStatement ps = conn.prepareStatement(query);
  ResultSet rs = ps.executeQuery();
  while (rs.next()) {

    Ordine ord = new Ordine();
    ord.setConsegnato(rs.getBoolean("consegnato"));
    ord.setDataOra(rs.getString("dataOra"));
    ord.setIdOrdine(rs.getInt("idOrdine"));
    ord.setIdProdotto(rs.getInt("idProdotto"));
    ord.setPrezzoFis(rs.getDouble("prezzoFis"));
    ord.setPrezzoDig(rs.getDouble("prezzoDig"));
    ord.setIva(rs.getDouble("iva"));
    ord.setQuantitaDigitale(rs.getInt("quantitaDigitale"));
    ord.setQuantitaFisico(rs.getInt("quantitaFisico"));
    ord.setIdUtente(rs.getInt("idUtente"));
    result.add(ord);

  }

} catch (SQLException e) {

  e.printStackTrace();

}


return result;
}
/**
 * {@param} id: int.
 * {@return} ArrayList of Ordine.
 */

public synchronized ArrayList<Ordine> doRetrieveByUser(int id) {

PreparedStatement ps = null;
String query = "SELECT * FROM ordine WHERE idUtente = ?";
ArrayList<Ordine> result = new ArrayList<Ordine>();

try (Connection conn = ConPool.getConnection()) {

  ps = conn.prepareStatement(query);
  ps.setInt(1, id);
  ResultSet rs = ps.executeQuery();
  while (rs.next()) {

    Ordine ord = new Ordine();
    ord.setConsegnato(rs.getBoolean("consegnato"));
    ord.setDataOra(rs.getString("dataOra"));
    ord.setIdOrdine(rs.getInt("idOrdine"));
    ord.setIdProdotto(rs.getInt("idProdotto"));
    ord.setPrezzoFis(rs.getDouble("prezzoFis"));
    ord.setPrezzoDig(rs.getDouble("prezzoDig"));
    ord.setIva(rs.getDouble("iva"));
    ord.setQuantitaDigitale(rs.getInt("quantitaDigitale"));
    ord.setQuantitaFisico(rs.getInt("quantitaFisico"));
    ord.setIdUtente(rs.getInt("idUtente"));
    result.add(ord);

  }

} catch (SQLException e) {

  e.printStackTrace();

}

return result;
}
/**
 * {@param} data1: String.
 * {@param} data2: String.
 * {@return} ArrayList of Ordine.
 */

public synchronized ArrayList<Ordine> doRetrieveByDate(String data1, String data2) {

PreparedStatement ps = null;
String query = "SELECT * FROM ordine WHERE dataOra >= ? AND dataOra <= ?";
ArrayList<Ordine> result = new ArrayList<Ordine>();

try (Connection conn = ConPool.getConnection()) {

  ps = conn.prepareStatement(query);
  ps.setString(1, data1);
  ps.setString(2, data2);
  ResultSet rs = ps.executeQuery();
  while (rs.next()) {

    Ordine ord = new Ordine();
    ord.setConsegnato(rs.getBoolean("consegnato"));
    ord.setDataOra(rs.getString("dataOra"));
    ord.setIdOrdine(rs.getInt("idOrdine"));
    ord.setIdProdotto(rs.getInt("idProdotto"));
    ord.setPrezzoFis(rs.getDouble("prezzoFis"));
    ord.setPrezzoDig(rs.getDouble("prezzoDig"));
    ord.setIva(rs.getDouble("iva"));
    ord.setQuantitaDigitale(rs.getInt("quantitaDigitale"));
    ord.setQuantitaFisico(rs.getInt("quantitaFisico"));
    ord.setIdUtente(rs.getInt("idUtente"));
    result.add(ord);

  }

} catch (SQLException e) {

  e.printStackTrace();

}

 return result;
 }

}

starting first with doRetrieveAll method, i tried to do a

@Test
public void doRetrieveAll_Success() throws SQLException {
    assertNotNull(ordineDAO.doRetrieveAll());
}

But i need to know how to set the @BeforeAll in order to test this method. Can you please help me understanding how to set properly the test class? Thank you

vendredi 26 février 2021

Why my transformation of a for-loop code into a while-loop one failed?

In the process of playing with getting all the odd numbers from 30 to 40 in a javascript's while-loop, I have encountered the problem of not being able to equally transform my for-loop code, which solves this task, into its while-loop counterpart. My while-loop gives out an extra '41'. Was my transformation wrong or while-loop is essentially different from the for-loop in JavaScript?

const max = 40;
const min = 30;
for (let i = min + 1; i < max; i += 2) {
  console.log(i);
}
// 31 33 35 37 39


const max = 40;
const min = 30;
let i = min + 1;
while (i < max) {
  console.log(i);
  i += 2;
}
// 31 33 35 37 39 41

How can I mock an ApolloError with code argument in @apollo/client fro testing?

I'm trying to test how my client handles a specific error I throw in my server like this:

throw new ApolloError("No applicant found", "APPLICANT_NOT_FOUND");

My client depends on the extensions.code part of result to handle the error. But since ApolloError from the package @apollo/client apparently doesn't work the same as the one in the server I cannot mock an error accordingly.

This is my mock so far:

export const getApplicantNotFound: Mock = {
  request: {
    query: GET_APPLICANT,
    variables: { codigo: "1234509876" },
  },
  result: {
//on this line typescript says: expected 1 argument but got 2
    errors: [new ApolloError(
      "No applicant found with code 123450987",
      "APPLICANT_NOT_FOUND"
    )],
  },
};

Do I need to install the apollo-server package to use the ApolloError that has extensions.code in my client tests? Or is there some way to mock this error in the client?

TypeError: Cannot read property 'getContext' of null

I have created a game using canvas API and now I am testing using Jest. But when running a test for a simple function it throws me this error. my script tag is at the end of the HTML and I also added this event listener to wait for the DOM document.addEventListener("DOMContentLoaded", init,false);

jest

PASS tests/sum.test.js FAIL tests/mod.test.js ● Test suite failed to run

TypeError: Cannot read property 'getContext' of null

  20 |   const empty = 0;
  21 |   const nextPieceCanvas = document.querySelector("canvas#nextPiece") as HTMLCanvasElement;
> 22 |   const NPctx = nextPieceCanvas.getContext("2d")! as CanvasRenderingContext2D;
     |                               ^
  23 |   
  24 |   //Gameboard Canvas
  25 |   const canvas = document.querySelector("canvas#tetris") as HTMLCanvasElement;

  at Object.<anonymous> (src/ts/app.ts:22:31)
  at Object.<anonymous> (tests/mod.test.js:2:1)

Test Suites: 1 failed, 1 passed, 2 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.424 s Ran all test suites. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! tetris_ts@1.0.0 test: jest npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the tetris_ts@1.0.0 test script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: npm ERR! /home/alex/.npm/_logs/2021-02-26T22_46_02_771Z-debug.logenter code here

Does Jest runs automated tests?

Sorry I am very new and very bad in testing and I have to ask a silly question as I am trying to test a node.js, express, javascript app using Jest and I was wondering if I would be performing basic unit ,integration and system tests based on test cases written in a file "filename.test.js" and executing the command "npm test" on the console , I can consider those tests as automated or I have to use frameworks like Selenium to perform automated tests? I thought, as I would be running the test by using the command prompt every time I am testing to run those tests, those tests are still manual??

Thanks so much for the help!!

Make Cypress wait for all requests to finish

I started with the following snippet. I noticed that some of the requests were being cancelled early because .click() only waits for a specific element to reach an actionable state (Cypress Docs) - instead of waiting for all of the page requests to finish.

  cy.visit('/about');
  cy.get('.favorite').click()
  cy.visit('');
  cy.get('.favorites').children().its('length').should('eq', 1);

I wrote the following as a way to intercept all requests and make sure that they finish before moving to the next action. However, it does not seem to work as requests are still being cancelled.

  cy.visit('/about');
  cy.intercept({method: 'GET', url: '**'}).as('getAbout');
  cy.wait('@getAbout');

  cy.get('.favorite').click()
  cy.intercept({method: 'GET', url: '**'}).as('favorite');
  cy.wait('@favorite');

  cy.visit('');
  cy.intercept({method: 'GET', url: '**'}).as('getBaseUrl');
  cy.wait('@getBaseUrl');

  cy.get('.favorites').children().its('length').should('eq', 1);

How do I make cypress wait for ALL requests to finish?

Is there a way to accomplish this in such a way that I do not have to add .wait() after every single page visit or button click?

Thanks

How to use client id and client secret generated by Laravel Passport in a testing?

I'm working under TDD, and I'm making a test to get a token using Password Grant Tokens with Laravel Passport, I've made the test manually (sending a curl with the client id, client secret, user and password) to the endpoint, and it works! It returns me a token, I'm using a client id and a client secret generated by the php artisan passport:install --uuids command (I've already made all previous configurations)

But now I want to write the test to generate that token, I have this code:


public function test_request_token() {

        $email = "user@test.com";
        $password = "123456";

        // Create the user
        $this->post("api/register", [
            "email" => $email,
            "password" => $password,
            "password_confirmation" => $password
        ]);

        // Ask for a token
        $response = $this->post("oauth/token", [
            'grant_type' => 'password',
            'client_id' => '92d16637-6c65-42c4-9ba2-b940d8dc3d0b',
            'client_secret' => 'Sx20PJJkmED46X2HzvhoLPHeXnoE7sNp6hNqTdBw',
            'username' => $email,
            'password' => $password,
            'scope' => ''
        ]);

        dd($response);

        $response->assertStatus(200);

    }

But it doesn't work, those credentials (client id and client secret) are the credentials that the php artisan passport:install --uuids command gave me (and are the same credentials that I've used to make the manual test with a curl that works)

I've putted a dd() function there to see what was happening, and the error is Client authentication failed so I think the test aren't reading the credentials generated by Laravel, how can I do to use those credentials?

I've tried to get credentials from the POST /oauth/clients endpoint but it says that it needs a user logged in, but I don't want to create users, my application doesn't allow clients creation, I just need one client on my application, and that client is the generated by Laravel Passport, so how can I do this?

React Jest/Enzyme - Snapshots created files are too big (thousands of lines)

Everytime I create a snapshot for a specific component, it returns thousands of lines for it (like 80k) because it is showing an attribute called "theme" for a lot of selectors. how can I get rid of this attribute. I don't think it is necessary for me to test things.

Info about the project:

  • React cra
  • Grommet for components
  • JEST/ENZYME for tests

enter image description here

How can I get Auth::user() to return the user created using a factory in a test?

I am working with Laravel 8.25. I have a Service class that has the following method:

public function getUsersBusinessManagers()
{
    $user = Auth::user()->id;

    return $user->businessManagers;
}

My test for this method is:

public function testCorrectBusinessManagersRetrievedForUser()
    {
        $user = User::factory()
            ->hasAttached(
                BusinessManager::factory()->count(1),
                ['user_fb_bm_id' => 'test']
            )
            ->create();
    
        $businessManagerService = new BusinessManagerService();
        $usersBusinessManagers = $businessManagerService->getUsersBusinessManagers();


        $this->actingAs($user)->assertEquals($user->businessManagers()->first()->id, $usersBusinessManagers->first()->id);
}

When running the test, how can I get Auth:user() in my service class to return the user I create in my test? Currently Auth:user() is null when I run the test.

Appreciate any help or guidance.

Trying to find test and training errors for ridge regression as a function of sample size

I am using the Hitters dataset in R. Currently I fit a linear regression predicting Salary from all other covariates with varying sample sizes from 20 to 75 and I calculated the average test/training errors :

data("Hitters", package = 'ISLR')
Hitters = na.omit(Hitters)
set.seed(1)
train.idx = sample(1:nrow(Hitters), 75,replace=FALSE)
train = Hitters[train.idx,-20]
test = Hitters[-train.idx,-20]

errs <- rep(NA,56)
for (ii in 20:75){
  train.idx = sample(1:nrow(Hitters), ii,replace=FALSE)
  train = Hitters[train.idx,-20]
  test = Hitters[-train.idx,-20]
  train.lm <- lm(Salary ~., - Salary, data = train)
  train.pred <- predict(train.lm, train)
  test.pred <- predict(train.lm, data = test)
  errs[ii-19] <-  mean((test.pred - train$Salary)^2)
}
errs

Now I am trying to do the same with Ridge regression using those samples I created from before with a regularization parameter of 20. I tried:

x_train = model.matrix(Salary~., train)[,-1]
x_test = model.matrix(Salary~., test)[,-1]

y_train = train$Salary
y_test = test$Salary

#cv.out = cv.glmnet(x_train,y_train, alpha = 0)
#lam = cv.out$lambda.min


errs.train <- rep(NA, 56)
for (ii in 20:75){
  ridge_mod = glmnet(x_train, y_train, alpha=0, lambda = 20)
  ridge_pred = predict(ridge_mod, newx = x_test)
  #errs.test[ii] <- mean((ridge_pred - y_test)^2)
  errs.train[ii-19] <- mean((ridge_pred - y_train)^2)
}

errs.train

But all the errors are coming out the same. How can I fix this?

What version of NUnit 3 should I be using

I have successfully converted a testing solution from .NET 4.6.1 to .NET Core 3.1. Within the solution I reference NUnit.Console 3.12.0, NUnit.ConsoleRunner 3.12.0, NUnit.Engine 3.12.0, and NUnit3TestAdapter 3.17.0. All the latest stable bits. When running the tests within Visual Studio, all is well.

My challenge is when I use .\.nuget\packages\nunit.consolerunner\3.12.0\tools\nunit3-console.exe <reference to my .NET Core 3.1 test csproj> to execute the tests. I am getting an exception that is discribed here: The NUnit 3 driver encountered an error while executing reflected code (NUnit.Engine.NUnitEngineException). According to http://charliepoole.org/technical/nunit-engine-version-conflicts-in-visual-studio.html I should be paying attention to the versions of NUnit. I have changed my NUnit references to NUnit.Console 3.11.1, NUnit.ConsoleRunner 3.11.1, NUnit.Engine 3.11.1, and NUnit3TestAdapter 3.17.0. When using .\.nuget\packages\nunit.consolerunner\3.11.1\tools\nunit3-console.exe <reference to my .NET Core 3.1 test csproj> I am still getting the exception listed earlier. I changed my csproj version to be netstandard2.0 to see what happens; no luck getting NUnit executable to successfully run.

I did obtain the zipped folder of the NUnit solution. When using .\.nunit-console-3.12\bin\Debug\netcoreapp3.1\nunit3-console.exe <reference to my .NET Core 3.1 test csproj> no problems - all is well. So obviously I am doing something incorrectly since locally compile version works but NuGet version does not.

I need to use the NuGet installed version since that is what the build server will use to execute the tests. Ideas and/or suggestions on what I am doing incorrectly?

"Error: Nock: No match for request" How to quickly understand what doesn't match?

I often face this error (Error: Nock: No match for request) using Nock, but I find it hard to quickly understand what doesn't match in order to adjust.

I used to use nock(apiUrl).persist().log(console.log)(link) that was doing the job pretty well. But it's been deprecated and I've recently updated the dependancy. Therefore I need to adapt, yet I find it hard to grasp what info is interesting for my debugging.

How to get something similar to Jest, obviously comparing what was expected, and what was actually called for quick and straightforward debugging ?

Emulating real Android device Camera output

I have a real (physical) Android device connected to my PC via USB cable. App under test has a QR scanning step, and I would like to hijack the camera output and feed a static image to it. That way the QR scanning procedure can be automated. It is possible to communicate with the device by Android Debug Bridge.

I am aware of all the solutions regarding VIRTUAL android device, but how can this be achieved with a physical device? Preferably with CLI and ADB.

Thanks!

How can I locate a parent of an element know by child value using CodeceptJS

basically I have the following:

<div class="container">
  <div class="title">title 1</div>
</div>
<div class="container">
  <div class="title">title 2</div>
</div>
<div class="container">
  <div class="title">title 3</div>
</div>

I want to locate the container that has "title 2" as title, without Xpath Please. I mean just css selectors and codeceptJS functions. Is it possible to do it?

how to write python testscript using classes and methods

I have python code which checks for request. If request = open, it should open the file else it should create new file. How to write testscript using classes and methods to check the operation. I have written testscript by importing the file1.py file.

`

from file1 import *

file2 = file1('', 'scm10.db', 'c')
print("srdid after creating file is", file2.srdid)
file2 = file1('', 'scm10.db', 'open')
print("after opening file srdid is", file2.srdid)

srdid is the dictionary element and is initially set to zero.

I want the above code to be written using classes and methods.

How to parse JSON placed in resource folder in SpringBoot

Hi I am trying to parse a JSON that I have saved in a resource folder and test it. So I took these steps for now.

DataLoader.java

@Service
public class DataLoader {

private static ObjectMapper  objectMapper = defaultObjectMapper();

  private static ObjectMapper defaultObjectMapper(){
    ObjectMapper  defaultObjectMapper = new ObjectMapper();
    //defaultObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return defaultObjectMapper;
  }

  public static JsonNode parse(String str) throws IOException {
    return objectMapper.readTree(str);
  }

  public static <A> A fromJason(JsonNode node, Class<A> clazz) throws JsonProcessingException {
    return objectMapper.treeToValue(node, clazz);
  }

}

DataLoaderTest.java

public class DataLoaderTest {

    @Value("classpath:data/novo.json")
    Resource jsonSource;

    //private String jsonSource = "{\"title\":\"new book\"}";

    @Test
    public void parse() throws IOException {
        JsonNode node = DataLoader.parse(jsonSource);
        assertEquals(node.get("title").asText(), "new book");
    }

    @Test
    public void fromJson() throws IOException {
        JsonNode node = DataLoader.parse(jsonSource);
        Fruit pojo = DataLoader.fromJason(node, Fruit.class);
        System.out.println("Pojo title " + pojo.title);
    }

}

So when I test it with //private String jsonSource = "{\"title\":\"new book\"}"; everything is working fine.

When I try to load JSON file from resources folder I am getting error:

error: incompatible types: Resource cannot be converted to String JsonNode node = ApxDataLoader.parse(jsonSource);

Any help highly appreciated.

Migrating testcafe suite to TypeScript

We have a huge testcafe e2e tests database and as a part of TS migration I'm rewriting test helper files to TypeScript.

But when I import a .ts helper inside of a .js test, test run fails with a syntax error not recognizing TypeScript syntax.

What am I doing wrong and what's the right way to do it?

How to map nested JSON into object model and test it in SpringBoot

Hi everyone I have a nested JSON that I have to map into 3 object models. I have to create CarResponse, Car and CarValue models.

Here is my JSON file:

{
  "car": [
    {
      "shop": "Audi Germany",
      "date": 1573599600000,
      "values": [
        {
          "name": "Audi Xl",
          "age": "2020",
          "country": "Germany"
        },
        {
          "name": "Audi i",
          "age": "2021",
          "country": "France"
        },
        {
          "name": "Bmw Xl",
          "age": "2020",
          "country": "Spain"
        },
        {
          "name": "Citroen",
          "age": "1990",
          "country": "France"
        }
}]
}

So I created 3 modals.

public class CarResponse {

    List<Car> quotes = new ArrayList<Car>();
    //Getters setters
}

public class Car {

    private String shop;
    private String date;
 //Getters setters and toString
}

public class CarValue {

    private String name;
    private String country;
    private Long age;
    //Getters setters and toString
}

I am not sure if this is a right way. Because when I try to write a test on it, I am not sure where to start.

I created DataLoader class to read from JSON.

@Service
public class DataLoader {

  @Value("${DataLoader.url}") private String urlStr;

  public QuoteResponse load() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper.readValue(urlStrl, QuoteResponse.class);
  }

}

And how should I write a test for it now? Any advice highly appreciated> Thanks!

Serivce "entity" inside the controller getiing null object when test with testng & mockito and sends the response to the Bad Request i.e testfails

ControllerClass, entity object inside the controller getting null return from service.save when run with testng

@RestController
@RequestMapping("/api")
public class PostController{

 @PostMapping("/post")
public ResponseEntity<PostResponse> savePostInfo(@RequestBody PostRequest req) throws Exception {


    PostEntity entity = postService.savePost(req.getData()); 
   //above line returning null when testng test perform
   
    PostResponse response = new PostResponse();
    if (entity != null) {
     
        response.setId(req.getData().getPostId());
        response.setData(req.getData());
        response.setStatus(Status.SUCCESS);
        response.setMessage("Post Information Saved");
        response.setIsAuthenticated(Boolean.TRUE);
        return new ResponseEntity<>(response, HttpStatus.OK);

     } else {
         
        response.setStatus(Status.FAILURE);
        response.setMessage("Data not Saved");
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);

     }
   }
}

TestClass

@RunWith(SpringRunner.class)  
@ContextConfiguration(classes=PostController.class)
@WebAppConfiguration
@WebMvcTest
public class PostControllerTest extends AbstractTestNGSpringContextTests{

private static final Logger logger = LoggerFactory.getLogger(PostControllerTest.class);

@Autowired
private WebApplicationContext wac;

@Autowired
private PostController postController;

  @Autowired
  ObjectMapper mapper;


  @MockBean
  private PostService postServiceUT = mock(PostService.class);
     
  private MockMvc mockMvc;

before method

  @BeforeMethod
  public void init() {
  mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
  } 

test method, mockMvc.perform getting the status.BAD_REQUEST due to PostEntity entity = postService.savePost(req.getData()) returning null in testng test, Can someone help me how to write a test for above controller method.

 @Test
 public void savePostInfoTest() throws Exception {
    
       PostEntity entity =new PostEntity();

       entity.setAccountId(11);
       entity.setCampaignId(12);
       entity.setContent("one");
       entity.setDateTime("now");
       entity.setExternalAccountId(13);
       entity.setExternalLink("link1");
       entity.setPostId(14);
       entity.setStatusId(15);
       entity.setTypeId(16);
       
       PostRequest req = new PostRequest();

       req.setData(entity);
      
       PostResponse response = new PostResponse();
         
       response.setId(entity.getPostId());
       response.setData(entity);
       response.setStatus(Status.SUCCESS);
       response.setMessage("Post Information Saved");
       response.setIsAuthenticated(Boolean.TRUE);
            
        logger.info("-------inside logger info  before Mockito.when");
                    
          
            
        Mockito.when(postServiceUT.savePost(Mockito.any(PostEntity.class))).thenReturn(entity);
        
          logger.info("-------inside logger info  before mvc.perform");
          logger.info("-------------data ="+req.getData());
          
     
          
       mockMvc.perform(post("/api/post").contentType(MediaType.APPLICATION_JSON_VALUE)
                .accept(MediaType.APPLICATION_JSON).characterEncoding("UTF-8")
                    .content(mapper.writeValueAsString(req)))
                    .andDo(print())
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$.message", is("Post Information Saved")))
                    .andExpect(jsonPath("$.status", is("SUCCESS"))) 
                    .andExpect(jsonPath("$.isAuthenticated", is(true)));
        
}}

jeudi 25 février 2021

cypress redirects to the new url automatically on it("",()=>{}) function

/// <reference types="cypress"/>

cy.get("#email").type("cypress@cypress.com");
cy.get("#password").type("khuljasimsim");

const productName = 123;
let discount = 200;
let price = 0;

describe("add product", () => {
  it("login", () => {
    cy.visit("https://web-panels.herokuapp.com/store-login");
    cy.get("#email").type(userName);
    cy.get("#password").type(password);
    cy.get(".form-check-input").click();
    cy.get(".btn").click();
  });

  it("should route to add poduct", () => {
    cy.get(":nth-child(2) > .nav-link").click();
    cy.get(".leftBorder").click();
  });

  it("should not allow if price is 0(zero)", () => {
    // Error: Automatically redirecting to the new url https://web-panels.herokuapp.com/store-login
    price = 0;
    cy.get(":nth-child(2) > .form-group > .form-control").type(price);
    cy.get(":nth-child(2) > .form-group > .form-control").should(
      "have.text",
      ""
    );
  });

As I execute the cypress test, as it reaches to the third it. Test automatically calls cy.visit("https://ift.tt/3krsHor); which I even did write in the the third it. What is the solution to prevent it redirecting to the unexpected new URL(https://web-panels.herokuapp.com/store-login) and why it is being happened.

Following snippet is cypress test execution, you would find the new URL in the snippet. Cypress test execution logs

Use method across all Junit Test classes

I need to create the below method which i need to use in all my test classes ( which are in different packages).How can I make the method available for all test classes.Any efficient way ? I am using Junit 5 and Mockito

public  TodosObject getObject(){
TodosObject todosObject= new TodosObject()
//setter ommitted for brevity

return todosObject;

}

ReferenceError 'process not defined' when executing Cypress test

Trying to execute any of the tests leads to this error popping up.

I am using Cypress 6.5.0

Really clueless about what to do.

Sorry for the image, but it was much better to show it this way.

enter image description here

And also the StackTrace.

at Object../node_modules/is-ci/node_modules/ci-info/index.js (webpack:///node_modules/is-ci/node_modules/ci-info/index.js:5:1)
at __webpack_require__ (webpack:///webpack/bootstrap:19:1)
at Object../node_modules/is-ci/index.js (webpack:///node_modules/is-ci/index.js:3:18)
at __webpack_require__ (webpack:///webpack/bootstrap:19:1)
at Object.eval (webpack:///node_modules/cypress/lib/util.js:21:14)
at Object../node_modules/cypress/lib/util.js (http://localhost:37869/__cypress/tests?p=test/e2e/support/index.js:87250:31)
at __webpack_require__ (webpack:///webpack/bootstrap:19:1)
at Object.eval (webpack:///node_modules/cypress/index.js:9:14)
at Object../node_modules/cypress/index.js (http://localhost:37869/__cypress/tests?p=test/e2e/support/index.js:82972:31)
at __webpack_require__ (webpack:///webpack/bootstrap:19:1)
From previous event:
at runScriptsFromUrls (http://localhost:37869/__cypress/runner/cypress_runner.js:177985:98)
at Object.runScripts (http://localhost:37869/__cypress/runner/cypress_runner.js:177999:11)
at $Cypress.onSpecWindow (http://localhost:37869/__cypress/runner/cypress_runner.js:167733:19)

mockResolvedValueOnce return promise intead of given value

import products from "services/products";

jest.mock("services/products", () => {
    return {
        getProducts: jest
            .fn()
            .mockImplementation(() => Promise.resolve([product, product])),
    };
});

((products.getProducts as unknown) as jest.Mock).mockResolvedValueOnce([product, product]);

Why is this array of [product, product] when it gets to the code it's Promise {[product, product]}
And as a result i recive an error on that array map (array.map is not a function)

How to implement NUnit's NUnit.Engine.ITestEventListener

I would like to use NUnit.Engine.ITestEventListener within my test solution. Specifically I would be looking for end of the run <test-run...>.

I implemented the interface ITestEventListener within C# code within my test csproj. I set a break point within the interface. Within Visual Studio, I began debugging tests; never hit the break point. I then wondered if this is a NUnit Engine thing and MSTest knows nothing of it. Am I correct that MSTest will never hit my breakpoint with my class that implements ITestEventListener?

Alright lets try something else like writing out to the console log by using nunit3-console.exe to run the tests. My output within the interface never wrote a thing - everything else wrote out properly. So, what am I doing incorrectly?

using System;
using NUnit.Engine;
using NUnit.Engine.Extensibility;

namespace Learning.NUnitInterface
{
    [Extension]
    public class MyTestListener : ITestEventListener
    {
        public void OnTestEvent(string report)
        {
            Console.WriteLine("Hello there, here is your data: ");
            Console.WriteLine(report);
        }
    }
}
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="log4net" Version="2.0.12" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" />
    <PackageReference Include="NUnit" Version="3.13.1" />
    <PackageReference Include="NUnit.Console" Version="3.12.0" />
    <PackageReference Include="NUnit.ConsoleRunner" Version="3.12.0" />
    <PackageReference Include="NUnit.Engine" Version="3.12.0" />
    <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
    <PackageReference Include="System.Configuration.ConfigurationManager" Version="5.0.0" />
  </ItemGroup>

</Project>

What does 'not enough x observations' imply in R?

I'm trying to run a t-test in R Studio and I keep coming back with this error -->

Error in t.test.default(x = subset(mydata$InfMort, subset = mydata$SubSahCountryvariable == : not enough 'x' observations

Here's the code -->

with(mydata, 
  t.test(x = subset(mydata$InfMort, subset = mydata$SubSahCountryvariable == 1), 
         y = subset(mydata$InfMort, subset = mydata$ArabCountryvariable == 1), 
         alternative = "two.sided"))

Anyone have any idea what's going on? I'm a beginner level in R.

Android apk is perfect in Android Studio testing but fails on Google Play closed test

I am making a VPN app and it compiles perfectly in Android Studio with no error. Moreover, once it is sent to my phone, the same, it works perfectly: it connects to the VPNs,etc.

Once I upload the signed bundle to Google Play closed or internal testing, i download the app, install and i observe the following:

  1. It request to create the vpn tunnel
  2. Doesn't connect to the vpn servers at all

It is using the openvpn libraries.

I have had 56 builds so far trying in all ways to do it.

I have no clue as Google doesn't detect any important issue with app as well

Thank you in advance if you have any clue

test react component that use query and subscription with apollo client

Does anyone have a tip about testing react components that use query and subscriptions with apollo client? It seems like when you are using the <MockedProvider /> component with mocks and link props it just ignores the mocks. thanks for the help!!

Power Supply Management testing problem with tolerance

Depending the input voltage supply, 3 power supply mode should be defined as follows:

-in case the input voltage is less than 8.2V then the power supply mode is set to undervoltage -in case the input voltage is greataer than 17.6V than the power supply mode is set to overvoltage -otherwise the power supply mode is set to normalvoltage

Note: The voltage tolerance of the system measurement is 2%.

a) Define as many test scenarious to be sure that the functionality is correctly. b) Justify the testing strategy applied above.

Thank you

Bitbucket pipeline Your system is missing the dependency: Xvfb

I'm trying to add cypress to the bitbucket pipeline but it tells me that I need to install Xvfb and I don't know how to keep going. This is my bitbucket.pipelines.yml

#  Template NodeJS build

#  This template allows you to validate your NodeJS code.
#  The workflow allows running tests and code linting on the default branch.

image: node:14.15.4

pipelines:
  default:
    - step:
        name: Build
        script:
          - npm install
          - npm run lint
          - npm run cypress:run

This is my package.json scripts

"scripts": {
    "cypress:open": "cypress open",
    "cypress:run": "npx cypress run --record --key xxxxxxxxxxxx"
}

and the test are running fine locally enter image description here

But in the pipeline I'm getting this error:

+ npm run cypress:run
> wallet-frontend@0.1.0 cypress:run /opt/atlassian/pipelines/agent/build
> npx cypress run --record --key 70004462-62d4-42ce-b359-5bff73d8b001
It looks like this is your first time using Cypress: 6.5.0
[16:30:09]  Verifying Cypress can run /root/.cache/Cypress/6.5.0/Cypress [started]
[16:30:09]  Verifying Cypress can run /root/.cache/Cypress/6.5.0/Cypress [failed]
Your system is missing the dependency: Xvfb
Install Xvfb and run Cypress again.
Read our documentation on dependencies for more information:
https://on.cypress.io/required-dependencies
If you are using Docker, we provide containers with all required dependencies installed.
----------
Error: spawn Xvfb ENOENT
----------
Platform: linux (Debian - 9.13)
Cypress Version: 6.5.0
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! wallet-frontend@0.1.0 cypress:run: `npx cypress run --record --key xxxxxxxxx`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the wallet-frontend@0.1.0 cypress:run script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

is it a good idea to use before for multiple tests?

I have a class, which has multiple methods. I am looking at the test cases written by someone.

The tests look like this..

describe('this tests example class', () => {
   let classInstance;
   before(() => {
     classInstance = new ExampleClass();
   })

   describe("tests 1", () => {
      it("first test", () => {
    
      })

      it("second test", () => {
    
      })

   })

   describe("tests 2", () => {
      it("third test", () => {
    
      })

      it("fourth test", () => {
    
      })

   })

}

let's say ExampleClass has a function func1 which has a parameter number and it pushes this number in the global array of its own.

Now first test calls func1 and it passes 5 as a number. Now, first test does something else too, but nothing important. We can look at the second test now, which checks if the ExampleClass's array has the number 5.

So, the way this works now is first test puts something on the global classInstance and second test checks if it's there..

The question: Does these kind of tests ever make sense at all ? I think good approach would be to have beforeEach and each test would work on the new instance of classInstance, but i think that this would cause more code for the test cases. Would appreciate your comment on this.

How to verify text does not exist on a web page with assertions

I'm new to Test Cafe Studio and I'm trying to figure out how to verify text is not present on a web page. I would like the test to fail if the text is present. Any help would be appreciated.

Testing Python objects with complicated initialization

I find that I often want to have Python objects with complicated initialization:

class Foo(object):
    def __init__(self, thing):
        self.complicated_processing_A(thing)
        self.complicated_processing_B(thing)

In my code, I then create the object and all the complicated processing is done:

f = Foo(thing)

This is great except that testing the Foo class is really annoying because you need to do a lot of mocking.

Another option is to change __init__ so that it doesn't do much but then when I use the class, I need to carry out the extra steps:

f = Foo(thing)
f.complicated_processing_A(thing)
f.complicated_processing_B(thing)

Is there a good way to hide the details of a complicated class but also have clean testing code?

Testcafe: Multiple Windows with no storage events

My app uses the localStorage event to "communicate" across browser windows. But it seems that testcafe does not pulish the storage event to other browser instances.

Example:

<button onClick="setData()">Set</button>

<div id="test"></div>
<script>
window.addEventListener('storage', function(e) {  
 console.log('storage event');
 document.querySelector("#test").textContent = "received";
});

function setData(){
  console.log('SET');
  localStorage.setItem('superpower', 'heatvision');
  
 document.querySelector("#test").textContent = "clicked";
}

</script>

Test:

const { Selector } = require("testcafe");

fixture `Test`
    .page `http://localhost:8081`;

test("test", async t => {
    await t.openWindow("http://localhost:8081")
    await t.click("button")
    await t.expect(Selector("div").innerText).eql("clicked")
    await t.switchToPreviousWindow();
    await t.expect(Selector("div").innerText).eql("received")
})

Does anyone know if this is possible using testcafe?

How Do I validate Dynamic date changes in UI using Selenium Java

I have a dropdown with various Time Dimensions like Previous year, Previous Quarter, Previous - day, month, week, Custom date range etc. Based on the dropdown option I choose, the date format is represented as below: The below is for Previous Quarter

Date Range:10/01/2020 00:00:00(CST) - 12/31/2020 23:59:59(CST)

How Can I validate the date changes using Selenium Java with a reusable method for all the options.

Thanks in advance

Jest error after update "Cannot redefine property: useEffect"

Migrating jest from 25 to 26 and react from 16 to 17 resulted in an error for mocking react hooks, as they are not executed with enzyme shallow rendering.

Mocking code:

jest.spyOn(React, 'useEffect').mockImplementationOnce((fn) => fn());

React version: 17.0.1

Error msg:

    TypeError: Cannot redefine property: useEffect
    at Function.defineProperty (<anonymous>)

Does some workaround exist?

Automation Testing for Custom Web based Chatbots

I am working in a Custom web based chatbot application. I want to Automate the testing that we do whenever we make any changes to the bot. Since this is a web based bot, Should I use Selenium Framework and design the tests ! or Are there any Open Source Automation Test frameworks that are designed for Chatbots and supports Web based bots with Authentication ?

Handling of TimerService in Weld-Junit

I'm trying to setup a Weld-JUnit4 Test for a JavaEE Bean which uses a TimerService. The Application runs in a Wildfly Application Server an So the TimerService is injected into the bean via @ResourceAnnotation.

In Weld-JUnit I have to bind Resources via:
WeldInitiator.from(<Some class).bindResource(nameOfRessource, <TimerServiceMock>)

But this doesn't work. The mock will not be injected. So I tried @Resouce(name = "myTimer")in the JEE Bean. This doesn't work too. So I tried @Resouce(lookup = "myTimer")in the JEE Bean. This works in my Testcase. But in ProductionCode this will change the lookupbehaviour. So it is no valid solution.

How it is possible to Mock the TimerService in a WeldJunitTest? Is there any kind of default lookup for the java.ejb.TimerService?

Thank you for your help.

Best practices for mocking an emit when testing a child component in Jest (Vue)

I am testing a whole bunch of child components, and I'm running into something that I think is really bad practice. Whenever I hit an emit in a child component, it wants me to import the parent component, which then wants me to import and set up all of the other child components that parent calls. I want to be able to mock the emit in the child so that I can test that it is being called in general without testing the actual parent function that is being called, since that is tested in the parent component.

So for example:

myMethod() {
      //do something
      this.$emit('some-emit',someArgument);
      //do something else
    },

I want to be able to test myMethod and when it hits this.$emit for it to return some kind of mocked result, something like this:

it('should mock the emit', () => {
  const someEmitSpy = jest.spyOn($emit, someArg);
  myComponent.myMethod; // run this using someEmitSpy instead of this.$emit
  //expect blah blah
}

mercredi 24 février 2021

(ssg-wsg) how to get access to test environment? Is it allowed to create test courses (or any test data) in production environment?

To test SSG APIs, may I know is there any lower environment available to test functionality of the APIs by integrating our app? also is it allowed to create test data in production environment?

How to handle type error (Cannot read property ' ' of undefined ) in cypress

I am taking a screenshot of a certain page by "cy.matchImageSnapshot". The error is thrown (Cannot read property ' ' of undefined). How can I resolve/ignore this? I have added my code and a screenshot of the console.

    describe('Test', () => {
    it('Testcase 1', () => {
      cy.on('uncaught:exception', (err, runnable) => {
        expect(err.message).to.include('of undefined')
        done()
        return false
      })
      cy.visit("https://www.damensch.com/?root=logo")
      cy.wait(10000)
      cy.contains('Allow').click()
      cy.scrollTo(0, 10000)     
      cy.scrollTo(10000, 0)
      cy.wait(5000)
      cy.matchImageSnapshot();        
    });

Console Screenshot after adding cy.on('uncaught:exception')

Console Screenshot without adding cy.on('uncaught:exception'

Index.js Screenshot

Does Cocoapods support test plans?

Like the title said,

I'm developing a pod library (namely MyLib) that is using test plans for Unit Tests.

Now I've add MyLib to a main project (MainProject), and MainProject is using conventional test targets for running UTs instead of test plans.

Is there anyway I can run MyLib's test plans from MainProject's scheme? I've read through Cocoapods documents and haven't found anything related to test plans.

issue while installing FindBugs in NetBeans 8-2

I am trying to install findBugs on NetBeans 8.2 and I am getting the following error: enter image description here

Can you please help!

Thank you!

Cypress unable to run in Jenkins?

I'm trying to run the cypress test with jenkins in my workplace. Due to Proxy issue I have uploaded my local node modules in s3 and before running the test I will download those modules and then run the test using this command.

But I'm getting below error Which I haven't understood. Can someone please explain what's wrong here ?

CYPRESS_CACHE_FOLDER=./cypress-cache ./node_modules/.bin/cypress run --headless --browser chrome --spec cypress/integration/api/api-test.spec.ts
The cypress npm package is installed, but the Cypress binary is missing.

We expected the binary to be installed here: /home/jenkins/agent/workspace/test-builds/cypress-ui-test-build/cypress-cache/6.1.0/Cypress/Cypress

Reasons it may be missing:

- You're caching 'node_modules' but are not caching this path: /home/jenkins/.cache/Cypress
- You ran 'npm install' at an earlier build step but did not persist: /home/jenkins/.cache/Cypress

Properly caching the binary will fix this error and avoid downloading and unzipping Cypress.

Alternatively, you can run 'cypress install' to download the binary again.

https://on.cypress.io/not-installed-ci-error

----------

Add as much detail as you can [closed]

So I have been looking at a C program code for the below coding, need to get output but unable to get it

#include <stdio.h>
#include <stdlib.h>

void instructions(){
    
    system("cls");
    printf("Instructions");
    printf("\n----------------");
    printf("\n Avoid Cars by moving left or right. ");
    printf("\n\n Press 'a' to move left");
    printf("\n Press 'd' to move right");
    printf("\n Press 'Esc' to exit");
    printf("\n\n Press any key to go back to menu");
    getch();
}


int main()
{
    
    
        system("cls");
        printf("--------------------------\n");
        printf("         Car game         \n");
        printf("--------------------------\n");
        printf("1. Start game\n");
        printf("2. Instructions\n");
        printf("3. Quit\n");
        printf("Select Option: \n");
        scanf("%d");
        char op = getche();
        
        if( op=='1') //play();
        else if ( op=='2' instructions();
        else if( op=='3') //exit(0);
        
   while(1);
   
   return 0;
}

How do I create a Unit test in Java?

I have a java class that takes an array of numbers and an array of corresponding probabilities and acts as a random number generator that returns one of the numbers from the array according to the corresponding probabilities defined in the other other. How do I write a minimal but effective set of unit tests?

class RandomGen{

    private int[] randomNums;
    private float[] probabilities;
    private float[] total_prob;

    RandomGen(int[] randomNums, float[] probabilites) throws Exception{
        if (this.set_arrays(randomNums, probabilites));
        else {
            throw new Exception("Invalid array format");
        }
    }

    private boolean set_arrays(int[] randomNums, float[] probabilities){
        if (check_arrays(randomNums, probabilities)) {
            this.randomNums = randomNums;
            this.probabilities = probabilities;
            this.total_prob = new float[this.probabilities.length];

            total_prob[0] = probabilities[0];
            for (int i = 1; i < probabilities.length; i++){
                total_prob[i] = total_prob[i-1] + probabilities[i];
            }
            return true;
        }
        return false;
    }

    public int[] return_randomNums(){
        return this.randomNums;
    }

    public float[] return_probabilites(){
        return this.probabilities;
    }

    private boolean check_arrays(int[] randomNums, float[] probabilities){
        float total_prob = 0;
        for (int i = 0; i < probabilities.length; i++){
            if (probabilities[i] < 0) return false;
            total_prob += probabilities[i];
        }
        if (randomNums.length != probabilities.length || total_prob != 1) return false;
        return true;
    }

    public int nextNum(){
        float random = (float) Math.random();
        if (random <= total_prob[0]){
            return randomNums[0];
        }
        for (int i=1; i < total_prob.length; i++){
            if (total_prob[i-1] < random  && random <= total_prob[i]) return randomNums[i];
        }
        return 0;
    }
}

WebfluxTest and MockBean

I've got problem with mock. It's null. Could you help me?

  1. UsersService
public interface UsersService {
    Mono<GetUserDto> findById(String id);
    Mono<GetUserDto> findByUsername(String username);
    Mono<CreateUserResponseDto> create(Mono<CreateUserDto> createUserDtoMono);
}
  1. RoutingHandlers
package com.app.routing;

import com.app.dto.CreateUserDto;
import com.app.service.UsersService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
public class RoutingHandlers {

    private final UsersService usersService;

    public Mono<ServerResponse> register(ServerRequest serverRequest) {
        Mono<CreateUserDto> createUserDtoMono = serverRequest.bodyToMono(CreateUserDto.class);
        var create = usersService.create(createUserDtoMono);
        return toServerResponse(create, HttpStatus.CREATED);

    }

    public Mono<ServerResponse> findByUsername(ServerRequest serverRequest) {
        String username = serverRequest.pathVariable("username");
        return toServerResponse(usersService.findByUsername(username), HttpStatus.OK);
    }

    public Mono<ServerResponse> findById(ServerRequest serverRequest) {
        String id = serverRequest.pathVariable("id");
        return toServerResponse(usersService.findById(id), HttpStatus.OK);
    }

    private static <T> Mono<ServerResponse> toServerResponse(Mono<T> mono, HttpStatus status) {

        return mono
                .flatMap(item -> ServerResponse
                        .status(status)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(item)))
                .doOnError(err -> {
                    System.out.println("---------------------------- ERROR -----------------------------");
                    System.out.println(err);
                    System.out.println("----------------------------------------------------------------");
                })
                .onErrorResume(e -> ServerResponse
                        .status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(e.getMessage())));
    }
}

  1. Routing
package com.app.routing;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RouterFunctions.nest;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;

@Configuration
public class Routing {

    @Bean
    public RouterFunction<ServerResponse> routerFunction(RoutingHandlers routingHandlers) {
        return nest(
                path("/users"),
                route(POST("").and(accept(MediaType.APPLICATION_JSON)), routingHandlers::register)
                        .andRoute(GET("/username/{username}").and(accept(MediaType.APPLICATION_JSON)), routingHandlers::findByUsername)
                        .andRoute(GET("/id/{id}").and(accept(MediaType.APPLICATION_JSON)), routingHandlers::findById)
        );
    }

}

  1. RoutingTest
package com.app;

import com.app.dto.CreateUserDto;
import com.app.dto.CreateUserResponseDto;
import com.app.routing.Routing;
import com.app.routing.RoutingHandlers;
import com.app.service.UsersService;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {RoutingHandlers.class, Routing.class})
@WebFluxTest
class RoutingTest {

    @Autowired
    private ApplicationContext applicationContext;

    @MockBean
    private UsersService usersService;

    private WebTestClient webTestClient;

    @BeforeEach
    public void setup() {
        webTestClient = WebTestClient.bindToApplicationContext(applicationContext).build();
    }

    @Test
    public void test1() {
        var userBody = CreateUserDto
                .builder()
                .username("u")
                .password("1234")
                .passwordConfirmation("1234")
                .build();

        var body = Mono.just(userBody);

        var userResponse = CreateUserResponseDto
                .builder()
                .id("1")
                .username("u")
                .build();

        var response = Mono.just(userResponse);

        Mockito
                .when(usersService.create(body))
                .thenReturn(response);

        webTestClient
                .post()
                .uri("/users")
                .accept(MediaType.APPLICATION_JSON)
                .body(body, CreateUserDto.class)
                .exchange()
                .expectStatus().isCreated()
                .expectBody(CreateUserResponseDto.class)
                .value(createUserResponseDto -> {
                    Assertions.assertThat(createUserResponseDto)
                            .hasFieldOrPropertyWithValue("username", "u")
                            .hasFieldOrPropertyWithValue("password", "1234");
                });
    }
}

  1. DTOs
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class CreateUserDto {
    private String username;
    private String password;
    private String passwordConfirmation;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class CreateUserResponseDto {
    private String id;
    private String username;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class GetUserDto {
    private String id;
    private String username;
    private String password;
}

After I ran test I got error: Cannot invoke "reactor.core.publisher.Mono.flatMap(java.util.function.Function)" because "mono" is null. In RoutingHandlers in register method instance called create is null:

public Mono<ServerResponse> register(ServerRequest serverRequest) {
        Mono<CreateUserDto> createUserDtoMono = serverRequest.bodyToMono(CreateUserDto.class);
        var create = usersService.create(createUserDtoMono);
        return toServerResponse(create, HttpStatus.CREATED);

    }

Rstudio: prop.test multiple labels

I have at my disposal the following database

dataset <-data.table(CORRECT=c(52,78,18,27,40,85,59,90), 
TOTAL=c(60,96,26,35,45,85,65,96), 
RANDOMIZATION=factor(c("Control","Test")), 
CASE=factor(c(1,1,2,2,3,3,4,4)))
dataset[, PROP := CORRECT/TOTAL]

I would like to make a comparison test of two proportions (p.value) for each CASE (1,2,3,4) according to RANDOMIZATION (Control, Test) in order to obtain the following table:

CORRECT TOTAL RANDOMIZATION CASE PROP PVALUE
52 60 Control 1 0.86 x.xx
78 96 Test 1 0.81
18 26 Control 2 0.69 x.xx
27 35 Test 2 0.77
40 45 Control 3 0.89 x.xx
85 85 Test 3 1.00
59 65 Control 4 0.91 x.xx
90 96 Test 4 0.94

The idea is then to obtain the following graphical representation :

GRAPH