mercredi 31 mars 2021

Request Parameter Security Testing

I am using security testing for my java web application which is build on struts framework. The very first vulnerability I found by burp suit that, I am able to change request parameter values. Now how we can validate these values if some one changing parameter values. For ex. Name is passing with some value "Jhon",now by burp suit if I change this value to "Smith", then this value will be saved in my database. How I will validate this.

In the same way i am using captcha validation. This is also I am able to change from burp suit. Can any one please let us know how to handle this.

Thanks

Number of requests = numbers of user

I have a question and I appreciate any help.

To make long story short Days ago in a meeting with a qa we talk about the differences between # request and # of users in a case.

I think is different but depends of the case, when I used a service o something like that it doesn't matter, because 1 user perform 10 request in one minute is the same than 10 user perform each 1 request in the same time

But For example if I need to validate the service's throughput send 1000 request in 1 hour, does it matters if I send 1000 request but not from 1000 users in 1 hour?

I want to know other perspective and know other opinions

Thanks in advance for any help

Sorry in advance for the english

With Julia, is there a way to create a test/temporary/throwaway environement?

I would like to test the installation of a certain combination of packages without polluting my primary environment and without needing to create a folder. Is there a way to do this interactively/in the REPL?

@testing-library/react with msw/node; window.fetch not returning body on POST

I created a simple application using create-react-app. I am now trying to write some automated test cases using @testing-library and Mock Service Worker. For reasons unknown to me when I POST a request using Window.fetch (or just fetch) the body of the response is not returned.

I am using the following dependencies:

    "@testing-library/react": "^11.2.5",
    "@testing-library/user-event": "^12.7.1",
    "msw": "^0.28.0",
    "react": "^17.0.1"

I have the following test:

import { rest } from 'msw';
import { setupServer } from 'msw/node';

const MOCKED_URL = 'http://mock.example.net:8080/foo'
let server = setupServer(
    rest.post(MOCKED_URL, (req, res, ctx) => {
        return res(
            ctx.status(200),
            ctx.json(req.body),
        )
    }),
)

beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

test('send POST request with body via superagent', async () => {
    let response = await window.fetch(MOCKED_URL, {
      method: 'POST',
      mode: 'cors',
      cache: 'no-cache',
      headers: { 'Content-Type': 'application/json' },
      body: { bar: 6, baz: '34' }
    });

    console.log(response);
    expect(response.body).toMatchObject({
        bar: 6,
        baz: '34',
    })
});

The output from the console.log(response) is

        type: 'default',
        status: 200,
        ok: true,
        statusText: 'OK',
        headers: Headers {
          map: { 'x-powered-by': 'msw', 'content-type': 'application/json' }
        },
        url: '',
        bodyUsed: false,
        _bodyInit: Blob {},
        _bodyBlob: Blob {}
      }

Can anyone explain why the body is not returned and how I can get this test to work?

Android Open Testing Developers Console

Create Open Testing Release error. The error is "You need to add a full description", but I can't for the life of me find where I can right a full description. In Edit Release, the only field with multiline capability is release notes. I have filled this in with a description of my app, but it does not solve the problem. Thanks in advance for any response.

Testing a react component axios post request

I have a React component that does a post request to my api to the recipes/search endpoint.

const recipeSearch = ({ setRecipes }) => {
    const [flavorType, setFlavorType] = useState({
        flavor_type: 'Sour',
    });

    const { flavor_type } = flavorType;

    const [loading, setLoading] = useState(false);

    const onChange = (e) => setFlavorType({ ...flavorType, [e.target.name]: e.target.value });

    const onSubmit = (e) => {
        e.preventDefault();

        const config = {
            headers: {
                'Content-Type': 'application/json',
            },
        };

        setLoading(true);
        axios
            .post(
                `${process.env.REACT_APP_API_URL}/recipes/search/`,
                {
                    flavor_type,
                },
                config
            )
            .then((res) => {
                setLoading(false);
                setRecipes(res.data);
                window.scrollTo(0, 0);
            })
            .catch(() => {
                setLoading(false);
                window.scrollTo(0, 0);
            });
    };

    return (
        <div data-testid='RecipeSearch'>
            <form onSubmit={(e) => onSubmit(e)}>
                <div>
                    <div>
                        <div>
                            <label htmlFor='flavor_type'>Choose Flavor</label>
                            <select name='flavor_type' onChange={(e) => onChange(e)} value={flavor_type}>
                                <option value='Sour'>Sour</option>
                                <option>Sweet</option>
                                <option>Salty</option>
                            </select>
                        </div>

                        <div>
                            {loading ? (
                                <div>
                                    <Loader type='Oval' color='#424242' height={50} width={50} />
                                </div>
                            ) : (
                                <button type='submit'>Search</button>
                            )}
                        </div>
                    </div>
                </div>
            </form>
            <div>{testing}</div>
        </div>
    );
};

recipeSearch.propTypes = {
    setRecipes: PropTypes.func.isRequired,
};

export default recipeSearch;

When the form is submitted the onSubmit function is called which in turn does post request to my backend api

axios
            .post(
                `${process.env.REACT_APP_API_URL}/recipes/search/`,
                {
                    flavor_type,
                },
                config
            )

I want to test that the request is indeed sent to the correct url.

I am using the React Testing Library and would like to know what is the correct way to do this using the jest-mock-axios library

Write a unit test class for an existing function that requires mockup within the function

I have a bunch of PHP functions that require unit test classes to be written. I just want to know is there any way to mock-up lines of a function before use assertions?

<?php 

function get_Func($args){
    $number = $args[0];
    $id = "71"+$args[1]+"0";

//The Line I need to mockup without touching the code
    $result = getViaCurl($number,$id);

    return $result;
}

?>

How to create a Junit test for the below code

I am able to get the coverage for the second and the third condition but not able to get the coverage for the last and the first one.

@Override public boolean equals(Object obj)
    {
        if(this == obj) {
            return true;
        }
        if(obj == null)
        {
            return false;
        }
        if(getClass() != obj.getClass()) {
            return false;
        }
        Rating other = (Rating) obj;
        boolean bool= score == other.score ;
        boolean bool2=Objects.equals(user, other.user);
        return bool&&bool2;
        
    }

the below one is my test function

    public void equalsTest_lastcondition() {
        Rating test=new Rating();
        
        Object obj2=testwa2;
        Rating other = (Rating) obj2;
        boolean bool=false;
        if(other.getScore()==testwa1.getScore())
        { bool=true;}
        boolean bool2 =Objects.equals(test.getUser(), other.getUser());
        assertEquals(true, bool && bool2);
    }   

Testlink | Not able to see any option for create new project |

I downloaded the testlink from bitnami for mac. After downloading the dmg files and launching the bitnami testlink , i am able to launch the testlink username and password page. after that login i can see only account setting page and nothing. please help me to intstall it locally on my system. enter image description here

What is this asking me to do on the second line?

        DateTime now = DateTime.Now;
        MainClass t = new OtherClass(now, 1, 1);
        Assert.AreEqual("Join", t.TransactionType);

What does the 2nd line mean?

Spring boot testing Rest Controller [closed]

What is the best and easiest solution to test this get mapping? Could you show some easy example?

@GetMapping("/locations")
public List<Location> allAccess() {
    return locationService.getLocations();
}

POST request fails (rest-assured test) Expected response body to be verified as JSON, HTML or XML but no content-type was defined in the response.?

I have problem with making POST request with rest-assured. @Test public void deleteBook(){

    //Given
    
    Response response = given().
        contentType("application/json").
        body(" { \"Title\": \"Libro2\"}").
    when().
        post("api/books/").andReturn();
    
    int id = from(response.getBody().asString()).get("id");
        
    //When
    when().
        delete("api/books/{id}",id).
    //Then  
    then().
        statusCode(200).
        body("id", equalTo(id));
    
    when()
        .get("api/books/{id}",id).
    then()
        .statusCode(404);
}

java.lang.IllegalStateException: Expected response body to be verified as JSON, HTML or XML but no content-type was defined in the response. Try registering a default parser using: RestAssured.defaultParser(); I have run out of ideas whats wrong.

Auto Populate Test Data for Moodle 3.*

Is there any way I can populate test data of Users, Course, course categories, cohert, group, Submissions, attempts, etc for testing purpose.

other text cases for basic function challenge in hackerank

I am trying to solve this hackerrank challenge.The code gives the right solution and passes the basic test case, however, two other test cases fail. I prefer this approach of solving the problem. Please assist me pass the other test cases thanks in advance. Here is my code:

function factorial(n){
    let myNum = n;
    let res;

    if(myNum === n){
        res = myNum * (n -1);
        myNum = n - 1; 
    }

    if(myNum > 0){
        res = res * (myNum - 1);
        myNum --;
    }
    return res;
}

Espresso - checking recyclerview position for specific image

I'm having a hard time figuring out how to test whether or not a certain image is being show on a position in a recyclerview using espresso. I have a list of people, and when one of them is selected, I'm showing a selected indicator around his image in the recyclerview. So I want to check that, for instance, position 0 has this indicator showing. What I'm trying is this:

fun test(position: Int, @DrawableRes res: Int): ViewInteraction {
    return onView(withId(recyclerViewId)).check(matches(hasItemAtPosition(position, hasBackground(res))))
}

 private fun hasItemAtPosition(position: Int, matcher: Matcher<View>): Matcher<View> {
    return object : BoundedMatcher<View, RecyclerView>(RecyclerView::class.java) {

        override fun describeTo(description: Description?) {
            description?.appendText("has item at position $position : ")
            matcher.describeTo(description)
        }

        override fun matchesSafely(recyclerView: RecyclerView): Boolean {
            val viewHolder = recyclerView.findViewHolderForAdapterPosition(position)
                ?: return false
            return matcher.matches(viewHolder.itemView)
        }
    }
}

This code works fine if I do it with withText rather than withBackground and match the text of the item.

The error I get looks like this:

androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'has item at position 0 : has background with drawable ID: 2131231310' doesn't match the selected view.
    Expected: has item at position 0 : has background with drawable ID: 2131231310

I'm kind of new to espresso and testing in general, so hoping someone has any suggestions.

How to test BLoC listening stream?

I want to test my chat_bloc file which listens several streams:

class ChatBloc extends Bloc<ChatEvent, ChatState> {
  final ChatRepository chatRepository;

  ChatBloc(
      {@required this.chatRepository,})
      : super(ChatLoading()) {

    this.add(ChatScreenStarted());

    _chatSubscription = chatRepository.message.listen((message) { // error points here
      // do smth
    });
  }

  StreamSubscription<Message> _chatSubscription;
  //  mapEventToState and others

  }

Message getter in ChatRepository:

@override
  Stream<Message> get message async* {
    yield* chatDataSource.messages;
  }

Mocking ChatRepository with mockito. And try to test like this:

class MockChatRepository extends Mock implements ChatRepository {}

void main() {
  MockChatsRepository mockChatsRepository;

  ChatBloc chatBloc;

  setUp(() {
    mockChatRepository = MockChatRepository();
    
    chatBloc = ChatBloc(
      chatRepository: mockChatRepository,
    );
  });

  blocTest(
    'sould ...',
    build: () => chatBloc,
    act: (ChatBloc chatBloc) {
      when(mockChatRepository.message)
          .thenReturn(Stream<Message>.fromIterable([tMessageModel]));
      chatBloc.add(ChatScreenStarted());
    },
    expect: () => [],
  );
}

Gives error NoSuchMethodError: The method 'listen' was called on null.

How can I stub that stream?

How to pass a variable in callbacks during rspec testing?

I have callback name authenticatie_admin_user . It will return true if current user email ID is "adminuser@admin.com"

def authenticate_admin_user!
 if Current.user.blank? || Current.user.email != "adminuser@admin.com"
  redirect_to courses_path, danger: "Admin login required" 
 end 
end

This callback runs when I call new action . While testing the new action I have to set Current.user value

describe "GET /new" do
    describe "Create course with admin login"
      it "will not renders a new course page" do
        get new_course_url
        expect(response).to_not be_successful
      end
      it "will render a new course page" do
        get new_course_url
        expect(response).to be_successful
      end
  end

How can I set the value of Current.user? PS: Here Current is a ActiveSupport::Currentattributes model and user is a attribute inside Current class.

mardi 30 mars 2021

Returning responses randomly from wiremock

I need to return a random response out of a predefined set each time the same wiremock endpoint is called. How can I do it?

Why keeping high code coverage constraints in R&D

Why in R&D there is still very high code coverage (>90%) when developing prototypes (no production) that use services that are quite unstable too? Sometimes I have the sensation that keeping this high code coverage is just slowing down the development with no real improvement because the code is changing fast. There is someone that is facing these same issues, if you have explanation why is acceptable to throw away this time with testing code that is very likely to change soon. Or if is maybe worth trying to explain that to the management? Most of the times I find myself just doing dumb tests only to comply to this constraints, I understand that this is not a good signal so I'm asking if and where I'm wrong and which action I could take to improve this. Thank you for your attention.

Is it possible to add the current time to each STEP in Allure reports?

Is it possible to add the current time to each STEP in Allure reports?

I am writing Automation using Java and TestNG. I was trying to search for an option to add the current time to each step, but could not find how to add it to the annotation without adding it as a parameter.

At the moment my Allure report looks like this:

  • Navigate to page 200ms
  • Click on Open button 250ms ....

I would like it to look something like this:

  • 15:00:00 Navigate to page 200ms
  • 15:00:01 Click on Open button 250ms

Thanks

Workflow from development to testing and merge

I am trying to formalize the development workflow and here's the first draft. Welcome suggestions on the process and any tweaks for optimization. I am pretty new when it comes to setting up the processes and would be great to have feedback on it. P.S: We are working on an AWS Serverless application.

Create an issue link in JIRA - is tested by. The link 'is tested by' has no relevance apart from correcting displaying the relation while viewing the story.

Create a new issue type in JIRA - Testcase. This issue type should have some custom fields to fully describe the test case.

For every user story, there will be a set of test cases that are linked to the user story using the Jira linking function. The test cases will be defined by the QA.

The integration/e2e test cases will be written in the same branch as the developer. E2E test cases will be written in a separate branch as it's a separate repository (Open for discussion).

The Test case issue type should also be associated with a workflow that moves from states New => Under Testing => Success/Failure

Additionally, we could consider adding capability in the CI system to automatically move the Test case to Success when the test case passes in the CI. (This should be possible by using JIRA API ). This is completely optional and we will most probably be doing it manually.

When all the Test cases related to a user story to success, The user story can then be moved to Done.

A few points to note:

We will also be using https://marketplace.atlassian.com/apps/1222843/aio-tests-test-management-for-jira for test management and linking.

The QA should be working on the feature branch from day 1 for adding the test cases. Working in the same branch will enable the QA and developer to be always in Sync. This should ensure that the developer is not blocked waiting for the test cases to be completed for the branch to be merged into development.

The feature branch will be reviewed when the pull request is created by the developer. This is to ensure that the review is not pending until the test cases have been developed/passed. This should help with quick feedback.

The focus here is on the "feature-oriented QA" process to ensure the develop branch is always release-ready and that only well-tested code is merged into the develop branch.

Testing in dart using Mockito and with new null safety rules

I may have misunderstood the null safety part, but I have a function that returns Future() and I'm just testing if it returns normally. That is where my issue begins because I have tried many ways to test if it returns void and with new null safety I can't return null and void isn't something you explicitly return. So how do you go about using the when().thenReturn() or when().thenAnswer()?

I've tried looking around here and other parts of the web but found nothing similar to my problem.

This is my test:

test(
  'should return void when a child data is being created in the database',
  () async {
    // arrange
    when(remoteDataSource.createData(
            collectionName, child0.toJson(), child0.uid!))
        .thenAnswer((_) {
      return Future<void>(() {});
    });
    // act
    final Either<Failure, void> result =
        await repository.createChildData(child0.uid!, child0);
    // assert
    verify(repository.createChildData(child0.uid!, child0));
    expect(result, equals(const Right<Failure, void>({})));
  },
);

Debug Output:

type 'Null' is not a subtype of type 'Future<void>'

package:grow_v1/features/grow/data/datasources/remote/firebase/grow_remote_datasoure.dart 73:16 MockRemoteDataSource.createData test/features/grow/data/repositories/child_repository_test.dart 89:31 main.. test/features/grow/data/repositories/child_repository_test.dart 87:7 main..

✖ Tests that should occur successfully should return void when a child data is being created in the database Exited (1)

how to populate a test function with given input-golang

I have the following code

func TestBookingListing_provisionHistory(t *testing.T) {
    Setup(false)

    b := Booking{
        
        Status: StatusActive,
    
        ListingIDs: []int64{1, 2},
    }

    for _, l := range b.ListingIDs {

        bl := BookingListing{
            BookingID:   b.ID,
            ListingID:   l,
            Created:     b.Created,
            Status:      StatusPending,
            RequestedBy: "Jane",
            Type:        b.Type,
            Updated:     b.Created,
        }

        
        if Status(bl.RequestedBy) != StatusExpired {

            t.Error("expecting status of bookinglisting to be requested")

        }

    }
}

I need to display the name of Requestedby in when the status is not expired. How can this be done thanking in advance

Validate that NUnit's ITestEventListener within Jenkins Pipeline for a netcoreapp3.1 assembly is called

Locally, I have successfully implemented the interface ITestEventListener within a C# netcoreapp3.1 csproj. However, when the tests are an within a Jenkins Pipeline, things appear to not be working(?).

I am using version 3.12.0 of NUnit.Engine.

By locally I am referring to using 1) Visual Studio Version 16.9.2 to run the tests and 2) command line dotnet test -c devint --test-adapter-path:. --logger:nunit to run the tests. I am getting successful test runs.

Success is my [Extension]public class ReportTestListener : ITestEventListener {...} generates an html file. I am to see the html file is created locally whereas from the Jenkins Pipeline the html file is not generated.

Within the Jenkins Pipeline, I am using the command sh "dotnet test -c ${env.TARGET_ENV} --test-adapter-path:. --logger:nunit" where env.TARGET_ENV resolves to devint. I know tests successfully run within the Jenkins Pipeline since the NUnit test results file is generated/published.

What I am not sure of is how to test/validate that the ReportTestListener is being called within the Jenkins Pipeline. I know that testing frameworks such as NUnit uses refection to identify test classes and methods. I am presuming that also happens with my implementation of [Extension]public class ReportTestListener : ITestEventListener {...}. Ideas/Suggestions on how to validate that ITestEventListener's method void OnTestEvent(string report) is being called besides writing out to disk?

Go 1.16.2 throwing "undeclared name" for all references in unit test files

for some reason i can run all of my Go functions across files in a directory with Go Run ... but everytime i create a unit test of the format "main_test.go" it throws the following error

go: go.mod file not found in current directory or any parent directory; see 'go help modules'

Here is my simple test:

package main

import "testing"

func TestMain(t *testing.T) {
    g := greetings()
    if g != "Hi There, Tony" {
        t.Errorf("Didnt return the right person!")
    }
}

1. COMPILATION ERROR and BUILD FAILURE occurred while running the Maven project (Selenium, Java) , Run As-> Maven test . 2. Error package org.testng

enter image description here

enter image description here

  1. COMPILATION ERROR and BUILD FAILURE occurred while running the Maven project (Selenium, Java) , Run As-> Maven test . 2. Error package org.testng

nodejs api route testing(mocha) failed due to timeout

i am new to nodejs testing with mocha and chai.right now I am having issue while testing a API route handler with mocha. my route handler code is

exports.imageUpload = (req, res, next) => {
    Upload(req,res, async () => {     
        //get the image files and its original urls (form-data)
        let files = req.files['files[]'];
        const originalUrls = req.body.orgUrl;
        // check the input parameters
        if(files == undefined || originalUrls == undefined){
          res.status(400).send({status:'failed', message:"input field cannot be undefined"})
        }
        if(files.length > 0 && originalUrls.length > 0){
          //array of promises
          let promises = files.map(async(file,index)=>{
            //create a image document for each file 
            let imageDoc = new ImageModel({
              croppedImageUrl : file.path,
              originalImageUrl: (typeof originalUrls === 'string') ? originalUrls : originalUrls[index],
              status: 'New'
            });
            // return promises to the promises array
            return await imageDoc.save();
          });
          // resolve the promises
          try{
            const response = await Promise.all(promises);
            res.status(200).send({status: 'success', res:  response});           
          }catch(error){
            res.status(500).send({status:"failed", error: error})
          }
        }else{
          res.status(400).send({status:'failed', message:"input error"})
        }      
    })
}

the Upload function is just a multer utility to store the imagefile and my test code is

describe('POST /content/image_upload', () => {
    it('should return status 200', async() => {
        const response = await chai.request(app).post('/content/image_upload')
                .set('Content-Type', 'application/form-data')
                .attach('files[]',
                 fs.readFileSync(path.join(__dirname,'./asset/listEvent.png')), 'asset')
                .field('orgUrl', 'https://images.unsplash.com/photo-1556830805-7cec0906aee6?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1534&q=80')
        
        expect(response.error).to.be.false;
        expect(response.status).to.be.equal(200);
        expect(response.body.status).to.be.equal('success');
        response.body.res.forEach(item => {
            expect(item).to.have.property('croppedImageUrl');
            expect(item).to.have.property('originalImageUrl');
            expect(item).to.have.property('status');
            expect(item).to.have.property('_id');
        })        
    })
})

and the output shown after running this code is

 1) POST /content/image_upload
       should return status 200:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/techv/content_capture/server/ContentServiceLib/api/test/image_upload.test.js)

Angular 8 karma test both success and error of Observable from service

I'm testing MyComponent that, in ngOnInit, calls a service method that returns an observable:

    this.myService.getMyData().subscribe(
        (data) => {
            //do something
        },
        (error) => {
            //do something - error
        }
    );

I've installed a spy on getMyData, this way:

mySpy = spyOn(myService, 'getMyData').and.returnValue(of(mockObject));

and this covers the "success branch" of subscribe. But I need also to cover the "error branch". I've tried doing this:

spyOn(myService, 'getMyData').and.returnValue(throwError(new Error('Error')));

but of course Jasmine tells me that getMyData has already been spied upon. How can I cover both branches?

Switch Driver from chrome to electron with java and Selenium

I am currently testing my application using chrome driver, but for one test I need to select a link to then open an electron app, after this i am unable to interact after the op up window has appeared. Is it possible to switch over to the electron app after ive launch the chromedriver? My driver class looks like this:

public static WebDriver startDriver() {


    String projectLocation = System.getProperty("user.dir");

    // add in elements for logging into the mobile application also - Android and
    // iOS.
    if (OSValidator.isMac()) {
        System.setProperty("webdriver.chrome.driver", projectLocation + "/chromedriver_mac");
    } else if (OSValidator.isWindows()) {
        System.setProperty("webdriver.chrome.driver", projectLocation + "/chromedriver.exe");
    } else {
        System.setProperty("webdriver.chrome.driver", projectLocation + "/chromedriver_linux");
    }

    if (System.getProperty("app.env") != null) { // If coming from Jenkins/Maven goal..
        // This is for logging results. Added when investigating crashes on chrome driver. Can be disabled when not needed. 26/03/2020
        System.setProperty("webdriver.chrome.verboseLogging", "true");
    }


    ChromeOptions options = new ChromeOptions();
    options.addArguments("start-maximized");
    options.addArguments("disable-infobars");
    options.addArguments("--disable-extensions");
    options.addArguments("--window-size=1920x1080");
    options.addArguments("--disable-cache");
    //options.addArguments("--headless");
    options.addArguments("--disable-application-cache");
    options.addArguments("--disk-cache-size=0");
    options.addArguments("--disable-gpu"); // applicable to windows os only
    options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
    options.addArguments("--dns-prefetch-disable");
    options.addArguments("--disable-notifications");
    options.addArguments("disable-infobars");


    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.BROWSER, Level.ALL);
    options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
    //options.addArguments("--no-sandbox"); // Bypass OS security model
    options.setPageLoadStrategy(PageLoadStrategy.NORMAL);
    driver = new ChromeDriver(options);
    //--------------------

    driver.manage().window().maximize();

    return driver;
}

Detox test fails on ios because of Health app

When I run detox test on iOS I got health access popup that and because of it detox hangs, I have permissions: { health: 'YES' }}); when I am launching my app, but I am trying to run it on CI, and my test always hangs because of this. Every time on new virtual machine I get this problem. Image https://i.stack.imgur.com/qsyZm.png

Failed to load module `App` in AppTests XCode

So I added a XCTest UnitTest folder in xcode (12.4) and tried to import my App to test some components of it.

However for seem reason I get the error

Failed to load module `App`

When I try to import my App

@testable import App

the App is called App as it is a generated PWA using Capacitor. I'm building for iOS.

I've looked all over this forum and StackOverflow but I have yet to see anyone with the same issue.

What am I missing here? Anyone any ideas?

Thanks

Cypress: How to test upload a folder with files and subfolders?

I'm having an issue to test uploading a folder with files and subfolders. If I add folder structure to the fixture then cy.fixture() command doesn't recognize that is a directory that I want to upload but it looks inside the directory to find the files. I have tries also to use the cy.readFile() but I couldn't make it to work.

I have tried to create drag and drop command like this:

Cypress.Commands.add('dragAndDropFolder', (fileUrl, type = '') => {
  return cy.readFile(fileUrl, 'binary')
    .then(Cypress.Blob.binaryStringToArrayBuffer)
    .then(blob => {
      const nameSegments = fileUrl.split('/');
      const name = nameSegments[nameSegments.length - 1];
      const testFile = new File([blob], name, { type });
      const event = {
        dataTransfer: {
          isDirectory: true,
          isFile: false,
          fullPath: `#${fileUrl}`,
          files: [testFile],
          items: [{ kind: 'file', type }],
          types: ['Files'],
        },
      };
      return cy
        .get('[data-test-dropzone="true"]')
        .first()
        .trigger('dragenter', event)
        .trigger('drop', event);
    });
});

Another thing I have tried to use a our different functionality which is simple upload button and the attachFile() plugin:

cy.readFile('client/testfolder', 'binary').then(file => {
          cy.get('#multiple_file_uploads_input').attachFile(file)
        });

Drag and drop functionality is written in Elixir and this is how data transfer looks like:

{
      isDirectory: true,
      isFile: false,
      fullPath: '#{path}',
      createReader() {
        return {
          sentEntries: false,
          readEntries(callback) {
            if (!this.sentEntries) {
              this.sentEntries = true;
              callback([#{Enum.join(entries, ",")}]);
            } else {
              callback([]);
            }
          },
        };
      },
    }

Unit test case not working in python selenium

I tries below unit test case and it doesnt open web browser and print directly "done" message.

from selenium import webdriver import unittest

class GoogleSearch(unittest.TestCase):

# driver = None

@classmethod
def setUpClass(cls):
    cls.driver = webdriver.Chrome(executable_path='../Drivers/chromedriver')
    cls.driver.maximize_window()

def test_search(self):
    self.driver.get('https://www.google.com')
    self.driver.find_element_by_name("q").send_keys("facebook")
    self.driver.implicitly_wait(10)
    self.driver.find_element_by_name("btnI").click()
    # driver.find_element_by_name("btnI").send_keys(Keys.ENTER)

@classmethod
def tearDownClass(cls):
    # driver.implicitly_wait(5)
    cls.driver.quit()
    cls.print("test completed")

print("done")

Read TestFixture parameters from derived class in base class in NUnit

I have problem in which I do not know how to read the TestFixture Parameters in my TestBase class given in my derived Test class.

The way I want to structure my test cases is by having many derived test classes which inherits from a base class. There are some logic I need to do in the base class which will apply to all my derived classes.

Base class

public abstract class TestBase
{
    [Test]
    public async Task ExecuteTestCaseAsync(string parameter1, string parameter2)
    {    
         // Some logic handling the parameters
                    
         await this.RunAsync();
            
         // Clean up
    }
        
    protected abstract Task RunAsync();
}

A derived class

    [TestFixture("parameter1", "parameter2")]
    public class Test1 : TestBase
    {
        protected override async Task RunAsync()
        {
            // Some logic
        }
    }

Is there a way to do that in NUnit?

Best practice for using codacy in my jenkins pipeline

Currently, I have subscribed to codacy pro.

And I want to use codacy in my Jenkins pipeline, and I found codacy-analysis-cli.

I tried to do a test on my local using this command: codacy-analysis-cli analyze --directory /home/codacy/backend-service --project-token --allow-network --verbose --upload

But when I checked app.codacy.com, there were no recent results.

Can you help me please? what is the best practice for using codacy in my jenkins pipeline.

lundi 29 mars 2021

Is it possible to have/emulate a GUI in a Windows Docker container from a Windows host?

Is it possible to have a GUI or emulate one in a Windows Docker container from a Windows host? Something similar like it is with XServer and Linux containers, or with Xvfb virtual display server and Linux containers. My goal would be to do automated GUI-testing of WPF and WinForms apps.

Unit testing by manipulating state variable - SwiftUI

I have a ContentView that generates a random paragraph.

import SwiftUI
import LoremIpsum

struct ContentView: View {
    @State private var text = ""
    @State private var wordCount: Int = 0
    
    var body: some View {
        ZStack(alignment: .topTrailing) {
            TextEditor(text: $text)
                .font(.body)
                .lineSpacing(16)
                .disableAutocorrection(true)
                .padding()
                .onChange(of: text) { value in
                    let words = text.split {
                        $0 == " " || $0.isNewline
                    }
                    self.wordCount = words.count
                }
            
            Text("\(wordCount) words")
                .font(.headline)
                .foregroundColor(.secondary)
                .padding(.trailing)
        }
        
        Button("Generate random text") {
            text = String.loremIpsum(paragraphs: 1)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

How would I create a unit test that tested for the correct wordCount and also if the text state corresponded to the loremIpsum paragraph?

I've tried playing about with the ViewInspector package that lots of people are discussing, although I'm not sure how you can actually manipulate the state with it.

Is this something that can be done with either unit or UI tests?

How do I test a function which is activated in another React component passed as prop?

I have a React class as such:

class EvidenceRelatedCases {
//...
    private handleAdd(selectedCases: []) {
         selectedCases.forEach(c => {
            // this is a GET request which I mocked
            CaseSource.get(c.id).then((fetchedCase) => {
            //do stuff; activates error message
            }
         }
    }

    render(
        return <div>
            <EntityPicker
                onAdd={this.handleAdd.bind(this)}
            />
}

I would like to test the handleAdd function, however, it is only executed inside the EntityPicker component so I'm having a hard time triggering it. This is what I currently have:

    it("should trigger error message when adding cases which are at limit capacity", () => {
        // trigger handleAdd() --> ??
        // mock get request
        // mock case that is to be returned from get request
        // check if error message displayed

        // mock get request; suppose to be called inside handleAdd()
        CaseSource.get.mockImplementation((caseId: string): Promise<ICaseModel> => {
            // mock maxed out case
            let caseModel = generateCase("1234");
            caseModel['Evidences'] = new Array(5000);
            return new Promise<ICaseModel>((resolve, reject) => { });
        });

        // trigger handleAdd(), (createView renders <EvidenceRelatedCases> with its props)
        const view = createView(context, evidenceId, true, [], [], null, null);
        view.handleAdd([/*one case object*/]);

        // verify if message is displayed
        const list = TestUtils.findRenderedComponentWithType(view, List as any) as List;
        console.log(list);

        const warning = TestUtils.findRenderedDOMComponentWithClass(list, "has-warning");

        expect(warning).toBeTruthy();
    });

The purpose is to check if an error message is displayed once the 'case' is full and the user still adds (handleAdd). The error and function to display error is in the EvidenceRelatedCases class component, however, the place where the function is triggered is in EntityPicker.

GoLang test fail due to quotes

I am using Drone CI to deploy golang applications however, local test results differs from drone test results basically, tests fail due to quotes or missing quotes in strings, like the following:

--- FAIL: TestFooImpl_POST (0.00s)
    --- FAIL: TestFooImpl_POST/bad_url_-_fail_to_create_request (0.00s)
        foo_test.go:75: values do not resemble:
            want [parse http://bad\url.com: invalid character "\\" in host name]
            got  [parse "http://bad\\url.com": invalid character "\\" in host name]

However, running locally, I get no such errors

=== RUN   TestFooImpl_POST/bad_url_-_fail_to_create_request
    --- PASS: TestFooImpl_POST/bad_url_-_fail_to_create_request (0.00s)

This is confusing and irritating as local and remote tests behave differently. False error results tend to be misleading

Any known reason for this? Or a way to solve?

Test Tableau with Selenium

I am trying to use selenium to control filters in Tableau reports on Tableau server.

The first challenge I am facing now is for reasons I don’t know both Xpath and CSS selector are unable to pick the webelements by ID. I am pretty sure there’s nothing wrong with what I passed into Xpath and CSS selector.

Anyone also had this issue and know how to make it work?

Wait till text in an element is changed

Please suggest if Selenium has a good option to wait until text will be changed within an element. Conditions:

  • Page is not autoreloaded
  • Element which text I need is dynamically reloaded
  • Time required for this data to be updated is unknown
  • Expected text is unknown. It is a timestamp.

I wrote a method which checks it every 1 second (or any time I set) and gets the value when it is changed. But I think there may be some better options. I try to avoid using time.sleep, but in the current case this is the only option I came to. Note, this text may change even after 5 minutes, so I will need to adjust the number of retries retries or time.sleep() Also, I use print just for debugging.

def wait_for_text(driver):  
    init_text = "init text"
    retry = 1
    retries = 120
    start_time = time.time()
    while retry <= retries:
        time.sleep(1)
        field_text = driver.find_element_by_id("my_id").text
        if field_text != init_text:
            break
        retry += 1
        now = time.time()
        total_time = now-start_time
        print(f"Total time for text to change {total_time}")
    print(f"Final field value: {field_text}")

(RSpec) How do I check if an object is created?

I want to test if expected exception handling is taking place in the following Ruby code through RSpec. Through testing I realized that I cannot use the raise_error matcher to test if the exception was raised, after rescuing it.

So, now I want to test whether objects of CustomError and StandardError are created to see if the error was raised as expected.

test.rb

module TestModule
  class Test
    class CustomError < StandardError
    end

    def self.func(arg1, arg2)
      raise CustomError, 'Inside CustomError' if arg1 >= 10 && arg2 <= -10
      raise StandardError, 'Inside StandardError' if arg1.zero? && arg2.zero?
    rescue CustomError => e
      puts 'Rescuing CustomError'
      puts e.exception
    rescue StandardError => e
      puts 'Rescuing StandardError'
      puts e.exception
    ensure
      puts "arg1: #{arg1}, arg2: #{arg2}\n"
    end
  end
end

test_spec.rb

require './test'

module TestModule
  describe Test do
    describe '#func' do
      it 'raises CustomError when arg1 >= 10 and arg2 <= -10' do
        described_class.func(11, -11)
        expect(described_class::CustomError).to receive(:new)
      end
    end
  end
end

When I run the above code I get the following error

 Failures:

  1) TestModule::Test#func raises CustomError when arg1 >= 10 and arg2 <= -10
     Failure/Error: expect(described_class::CustomError).to receive(:new)
     
       (TestModule::Test::CustomError (class)).new(*(any args))
           expected: 1 time with any arguments
           received: 0 times with any arguments
     # ./test_spec.rb:8:in `block (3 levels) in <module:TestModule>'

The idea was that if CustomError is being raised, it's obejct must be created using new and I can test that using RSpec. However, as you can see, this isn't working.

What am I missing?

Is there a better approach?

Test with jest message publish to service bus

I have an issue which is blocking me from some time. So, I have the following code:

Publisher.js

import { logger } from "logger";
import retry from "async-retry";

import publishMessage from "./publishMessage";
import saveFailedEvent from "./saveFailedMessage";

export default function publishWithRetry({
  message,
  topicName,
  connectionString,
  retries,
  minTimeout,
  maxTimeout,
  factor,
}) {
  return retry(() => publishMessage({ message, topicName, connectionString }), {
    retries,
    minTimeout,
    maxTimeout,
    factor,
    onRetry: (err, number) => {
      logger.log(
        "error",
        "false",
        `Retry number ${number}: Failed to send message`
      );
      if (number === retries) {
        saveFailedEvent({ message, topicName });
        logger.log(
          "error",
          "false",
          "Retries exhausted. Event will be saved in <colllection name> collection"
        );
      }
    },
  });
}

SaveFailedMessage.js

import { logger } from "logger";
import FailedMessageModel from "../../models/FailedMessageModel";

async function saveFailedMessage({ message, topicName }) {
  try {
    const payload = message;

    const eventError = {
      eventName: payload.body.event_name,
      publisher: payload.body.producer,
      destination: topicName,
      createdDateTime: Date.now(),
      payload,
    };

    await FailedMessageModel.create(eventError);
  } catch (err) {
    logger.log(
      "error",
      "false",
      `Failed to save FailedMessageModel in db${err}`,
      "saveFailedMessage",
      ""
    );
  }
}

export default saveFailedMessage;

and my test file:

import { ServiceBusClient } from "@azure/service-bus";
import EventService from '../../src/index';

jest.mock('@azure/service-bus', () => {
  return { 
    ServiceBusClient: jest.fn() 
  };
});

describe('Publish messages to azure service bus', () => {
  const sbConnection =
      "Endpoint=asdaasda";
  const events = new EventService({
    connection: sbConnection,
    retries: 3,
    minTimeout: 1000,
    maxTimeout: 1000,
    factor: 1,
  });
  it('should publish messages with success', async () => {
    const sendMessages = jest.fn();
    ServiceBusClient.mockImplementation(() => {
        return {
          createSender: jest.fn().mockReturnValue({
            sendMessages,
            close: jest.fn()
          })
        };
      })
        const message = {
      body: {
        message: "testing resiliance",
      },
    };
    events.publish({ message, topicName: "event_topic" })

    expect(sendMessages).toHaveBeenCalledWith(message)
  });

  it('should throw an error when publish message', async () => {
    const sendMessages = jest.fn().mockImplementation(() => {
      throw new Error('test error');
    });
    ServiceBusClient.mockImplementation(() => {
        return {
          createSender: jest.fn().mockReturnValue({
            sendMessages,
            close: jest.fn()
          })
        };
      })
        const message = {
      body: {
        message: "testing resiliance",
      },
    };
    events.publish({ message, topicName: "event_topic" })

    expect(sendMessages).toHaveBeenCalledWith(message)
  });
});

The problem is that I'm having issues covering the saveFailedMessage which is Imported as saveFailedEvent in Publisher.js . If somebody can help me a bit here, how should I write the test to cover this method also.

Question about cross-validation and what's next

Maybe it's a very simple question, but I'm just starting out. I have a list of vectors with which I want to do cross-validation, but I don't quite understand how I should do it. This is my code:

# scikit-learn k-fold cross-validation
from numpy import array
from sklearn.model_selection import KFold
import texture_wavelets as text_wav
import os
import cv2

# data sample
directory_images = 'D:/images'

results = []

for image_name in os.listdir(directory_images):
    image = cv2.imread(directory_images + "/" + image_name)
    mask = text_wav.TextureWavelets().create_mask_plaque(image, 'b&w')
    results.append(text_wav.TextureWavelets().waveletdescr(mask, maxlevel=2))

    data = results

# prepare cross validation
kfold = KFold(3, True, 1)
# enumerate splits
for train, test in kfold.split(data):
    print('train: %s, test: %s' % (data[train], data[test]))

This is data list:

[array([    0.        ,  2044.61238098,     0.        ,     0.        ,
        2618.09565353,     0.        , 39819.78557968]), array([    0.        ,  4071.92074585,     0.        ,     0.        ,
        2776.18331909,     0.        , 43219.63778687]), array([    0.        ,  3076.86044312,     0.        ,     0.        ,
        2464.76063919,     0.        , 44498.27956009]), array([   0.        , 5871.45904541,    0.        ,    0.        ,
       1783.31578445,    0.        , 5319.52641678]), array([   0.        , 4213.01197815,    0.        ,    0.        ,
       3044.87182617,    0.        , 5253.39610291]), array([   0.        , 4855.08622742,    0.        ,    0.        ,
       1976.97391891,    0.        , 6974.81827927]), array([    0.        ,  4719.39257812,     0.        ,     0.        ,
        3474.63452911,     0.        , 38802.29157257]), array([    0.        ,  5773.23097229,     0.        ,     0.        ,
        4237.98572159,     0.        , 17283.86447525]), array([    0.        ,  2585.32319641,     0.        ,     0.        ,
        2866.66228867,     0.        , 18270.41167831]), array([    0.        ,  2533.72865295,     0.        ,     0.        ,
        3004.23120117,     0.        , 43447.09034729])]

I get the following error:

print('train: %s, test: %s' % (data[train], data[test]))
TypeError: only integer scalar arrays can be converted to a scalar index

My question is, can I apply this code to my data? And how can I use the information afterwards? What kind of information will I get? Thank you very much!

How can I test function with logic inside sql querys?

My problem is that I have giant SQL queries that have logic inside them and need to be tested someway. I'm using PHP and trying PHPUnit together. I have tons of functions similar to this one, that has different levels of logic inside them and I need to automate tests to every single one. For example, queries where some content returned depends on multiple tables and states. An example in code:

<?php

use \somewhere\controller;

class cidade extends controller {
    // query() comes from controller, and it's a pdo query
    public function listar () {
        return $this->query(
            'SELECT 
                c.id, s.descricao, c.dataInicial, c.dataFinal, c.valor 
            FROM comissao c left join servico s ON (c.servico = s.id)
            WHERE (CURDATE() BETWEEN c.dataInicial AND c.dataFinal)
                OR (CURDATE() > c.dataInicial AND c.dataFinal IS NULL)'
        );
    }
}

That returns this enter image description here

If I use this setup (I created this only for example, in sqlfiddle.com)

CREATE TABLE IF NOT EXISTS `servico` (
  `id` int(6) unsigned NOT NULL,
  `descricao` varchar(50) NOT NULL
) DEFAULT CHARSET=utf8;
INSERT INTO `servico` (`id`, `descricao`) VALUES
  (1, 'Algo'),
  (2, 'Alguma coisa'),
  (3, 'Outra coisa');
  
CREATE TABLE IF NOT EXISTS `comissao` (
  `id` int(6) unsigned NOT NULL,
  `servico` int(6) unsigned NOT NULL,
  `dataInicial` date NOT NULL,
  `dataFinal` date,
  `valor` decimal(15,2) NOT NULL
) DEFAULT CHARSET=utf8;
INSERT INTO `comissao` (`id`, `servico`, `dataInicial`, `dataFinal`, `valor`) VALUES
  (1, '1', '2021-03-01', '2021-03-10', 12.30),
  (2, '2', '2021-03-01', '2021-03-10', 77.30),
  (3, '3', '2021-03-15', '2021-04-06', 1.30),
  (4, '1', '2021-03-28', NULL, 15.30),
  (5, '2', '2021-03-28', NULL, 6.30);

But in my day to day, I will change this database and it's gonna be complicated to change my tests to new results.

A little bit of what I already read about: I thought in to create a database just to test, but this would be a huge work to set up, so I started to look for a way to "create" a basic fake DB for these queries, but I could not find. So I just read about dbunit for a minute but seems like doesn't work with PHPUnit new versions, so I think that is deprecated. In some other places of PHPUnit documentation, I found things about dependency injection and mock my database results, but actually, I need to test what results I will get with my query, and not set results by myself.

Android Native contract testing

I have applications in Spring Boot, I need to write an Android application for it. At Spring Boot I use spring-cloud-contract to generate a stub. Can I somehow use this stub for Android contract testing, or maybe there is a better way for Android contract testing.

Angular 8 karma test if branch with environment variable

How can I test this branch in constructor of my service?

  constructor() {
    if (environment.logLevel) {
      this.minAcceptedLogLevel = environment.logLevel;
    }
  }

I know that I have to create a service for getting environment variables, but how can I change the value of that property to cover the two branches of the if condition, also being the check inside the constructor?

how to captor a hashmap inside a nested method in Mockito?

The class and its methods as follows.

Class MyClass{
   method1(){
      method2(para1)
   }

   method2(para1){
      HashMap<String,String> users=new HashMap<>();
      ...
      para1.setUsers(users)
   }
}

I want to captor the users hashmap for unit testings by mocking the MyClass. How I can complete this with mockito?

I want to run selenium with chrome browser in non-headless mode in a docker image with OS as centos, it possible?

I want to run selenium with chrome browser in non-headless mode in a docker image with OS as centos, it possible, if so please share some inputs

You are testing a contact form and you find that the HTML email it generates contains ASCII codes and partially rendered HTML tags [closed]

You are testing a contact form and you find that the HTML email it generates contains ASCII codes and partially rendered HTML tags. How would you grade this?

Critical

Conversion

CX

i uploaded my app on google play for internal testing but it is showing 9 warning

StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V at android.os.StrictMode.lambda$static$1(StrictMode.java:428) at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2) at java.lang.Class.getDeclaredMethodInternal(Native Method) at java.lang.Class.getPublicMethodRecursive(Class.java:2075) at java.lang.Class.getMethod(Class.java:2063) at java.lang.Class.getMethod(Class.java:1690) at androidx.appcompat.widget.ViewUtils.makeOptionalFitsSystemWindows(ViewUtils.java:84) at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:973) at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:806) at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:693) at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170) at com.example.bmicalculator.MainActivity.onCreate(MainActivity.kt:27) at android.app.Activity.performCreate(Activity.java:7144) at android.app.Activity.performCreate(Activity.java:7135) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at androidx.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:2) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2931) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3086) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816) at android.os.Handler.dispatchMessage(Handler.java:106) at androidx.test.espresso.base.Interrogator.loopAndInterrogate(Interrogator.java:10) at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:7) at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:1) at androidx.test.espresso.base.UiControllerImpl.injectMotionEvent(UiControllerImpl.java:6) at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:6) at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:1) at androidx.test.espresso.action.Tap.sendSingleTap(Tap.java:5) at androidx.test.espresso.action.Tap.access$100(Tap.java:1) at androidx.test.espresso.action.Tap$1.sendTap(Tap.java:1) at androidx.test.espresso.action.GeneralClickAction.perform(GeneralClickAction.java:4) at androidx.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:4) at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:19) at androidx.test.espresso.ViewInteraction.access$100(ViewInteraction.java:1) at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:2) at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:1) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6718) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

second warning StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V at android.os.StrictMode.lambda$static$1(StrictMode.java:428) at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2) at java.lang.Class.getDeclaredMethodInternal(Native Method) at java.lang.Class.getPublicMethodRecursive(Class.java:2075) at java.lang.Class.getMethod(Class.java:2063) at java.lang.Class.getMethod(Class.java:1690) at androidx.appcompat.widget.ViewUtils.makeOptionalFitsSystemWindows(ViewUtils.java:84) at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:973) at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:806) at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:693) at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170) at com.example.bmicalculator.Welcomer.onCreate(Welcomer.kt:16) at android.app.Activity.performCreate(Activity.java:7144) at android.app.Activity.performCreate(Activity.java:7135) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at androidx.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:2) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2931) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3086) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6718) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

second issue StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Landroid/graphics/FontFamily;->()V at android.os.StrictMode.lambda$static$1(StrictMode.java:428) at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2) at java.lang.Class.getDeclaredConstructorInternal(Native Method) at java.lang.Class.getConstructor0(Class.java:2325) at java.lang.Class.getConstructor(Class.java:1725) at androidx.core.graphics.TypefaceCompatApi26Impl.obtainFontFamilyCtor(TypefaceCompatApi26Impl.java:321) at androidx.core.graphics.TypefaceCompatApi26Impl.(TypefaceCompatApi26Impl.java:84) at androidx.core.graphics.TypefaceCompatApi28Impl.(TypefaceCompatApi28Impl.java:36) at androidx.core.graphics.TypefaceCompat.(TypefaceCompat.java:51) at androidx.core.graphics.TypefaceCompat.create(Unknown Source:0) at androidx.appcompat.widget.AppCompatTextView.setTypeface(AppCompatTextView.java:708) at android.widget.TextView.resolveStyleAndSetTypeface(TextView.java:2037) at android.widget.TextView.setTypefaceFromAttrs(TextView.java:2008) at android.widget.TextView.applyTextAppearance(TextView.java:3640) at android.widget.TextView.(TextView.java:1498) at android.widget.TextView.(TextView.java:869) at androidx.appcompat.widget.AppCompatTextView.(AppCompatTextView.java:100) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:93) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:88) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:83) at com.google.android.material.theme.MaterialComponentsViewInflater.createTextView(MaterialComponentsViewInflater.java:61) at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:115) at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1551) at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1602) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:772) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) at android.view.LayoutInflater.rInflate(LayoutInflater.java:863) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.inflate(LayoutInflater.java:515) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at android.view.LayoutInflater.inflate(LayoutInflater.java:374) at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696) at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170) at com.example.bmicalculator.MainActivity.onCreate(MainActivity.kt:27) at android.app.Activity.performCreate(Activity.java:7144) at android.app.Activity.performCreate(Activity.java:7135) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at androidx.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:2) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2931) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3086) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816) at android.os.Handler.dispatchMessage(Handler.java:106) at androidx.test.espresso.base.Interrogator.loopAndInterrogate(Interrogator.java:10) at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:7) at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:1) at androidx.test.espresso.base.UiControllerImpl.injectMotionEvent(UiControllerImpl.java:6) at androidx.test.espresso.action.MotionEvents.sendUp(Moti third issue StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Landroid/graphics/FontFamily;->abortCreation()V at android.os.StrictMode.lambda$static$1(StrictMode.java:428) at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2) at java.lang.Class.getDeclaredMethodInternal(Native Method) at java.lang.Class.getPublicMethodRecursive(Class.java:2075) at java.lang.Class.getMethod(Class.java:2063) at java.lang.Class.getMethod(Class.java:1690) at androidx.core.graphics.TypefaceCompatApi26Impl.obtainAbortCreationMethod(TypefaceCompatApi26Impl.java:343) at androidx.core.graphics.TypefaceCompatApi26Impl.(TypefaceCompatApi26Impl.java:88) at androidx.core.graphics.TypefaceCompatApi28Impl.(TypefaceCompatApi28Impl.java:36) at androidx.core.graphics.TypefaceCompat.(TypefaceCompat.java:51) at androidx.core.graphics.TypefaceCompat.create(Unknown Source:0) at androidx.appcompat.widget.AppCompatTextView.setTypeface(AppCompatTextView.java:708) at android.widget.TextView.resolveStyleAndSetTypeface(TextView.java:2037) at android.widget.TextView.setTypefaceFromAttrs(TextView.java:2008) at android.widget.TextView.applyTextAppearance(TextView.java:3640) at android.widget.TextView.(TextView.java:1498) at android.widget.TextView.(TextView.java:869) at androidx.appcompat.widget.AppCompatTextView.(AppCompatTextView.java:100) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:93) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:88) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:83) at com.google.android.material.theme.MaterialComponentsViewInflater.createTextView(MaterialComponentsViewInflater.java:61) at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:115) at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1551) at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1602) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:772) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) at android.view.LayoutInflater.rInflate(LayoutInflater.java:863) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.inflate(LayoutInflater.java:515) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at android.view.LayoutInflater.inflate(LayoutInflater.java:374) at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696) at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170) at com.example.bmicalculator.MainActivity.onCreate(MainActivity.kt:27) at android.app.Activity.performCreate(Activity.java:7144) at android.app.Activity.performCreate(Activity.java:7135) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at androidx.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:2) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2931) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3086) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816) at android.os.Handler.dispatchMessage(Handler.java:106) at androidx.test.espresso.base.Interrogator.loopAndInterrogate(Interrogator.java:10) at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:7) at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:1) at androidx.test.espresso.base.UiControllerImpl.injectMotionEvent(UiControllerImpl.java:6) forth issue StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Landroid/graphics/FontFamily;->addFontFromAssetManager(Landroid/content/res/AssetManager;Ljava/lang/String;IZIII[Landroid/graphics/fonts/FontVariationAxis;)Z at android.os.StrictMode.lambda$static$1(StrictMode.java:428) at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2) at java.lang.Class.getDeclaredMethodInternal(Native Method) at java.lang.Class.getPublicMethodRecursive(Class.java:2075) at java.lang.Class.getMethod(Class.java:2063) at java.lang.Class.getMethod(Class.java:1690) at androidx.core.graphics.TypefaceCompatApi26Impl.obtainAddFontFromAssetManagerMethod(TypefaceCompatApi26Impl.java:326) at androidx.core.graphics.TypefaceCompatApi26Impl.(TypefaceCompatApi26Impl.java:85) at androidx.core.graphics.TypefaceCompatApi28Impl.(TypefaceCompatApi28Impl.java:36) at androidx.core.graphics.TypefaceCompat.(TypefaceCompat.java:51) at androidx.core.graphics.TypefaceCompat.create(Unknown Source:0) at androidx.appcompat.widget.AppCompatTextView.setTypeface(AppCompatTextView.java:708) at android.widget.TextView.resolveStyleAndSetTypeface(TextView.java:2037) at android.widget.TextView.setTypefaceFromAttrs(TextView.java:2008) at android.widget.TextView.applyTextAppearance(TextView.java:3640) at android.widget.TextView.(TextView.java:1498) at android.widget.TextView.(TextView.java:869) at androidx.appcompat.widget.AppCompatTextView.(AppCompatTextView.java:100) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:93) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:88) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:83) at com.google.android.material.theme.MaterialComponentsViewInflater.createTextView(MaterialComponentsViewInflater.java:61) at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:115) at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1551) at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1602) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:772) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) at android.view.LayoutInflater.rInflate(LayoutInflater.java:863) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.inflate(LayoutInflater.java:515) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at android.view.LayoutInflater.inflate(LayoutInflater.java:374) at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696) at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170) at com.example.bmicalculator.MainActivity.onCreate(MainActivity.kt:27) at android.app.Activity.performCreate(Activity.java:7144) at android.app.Activity.performCreate(Activity.java:7135) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at androidx.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:2) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2931) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3086) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816) at android.os.Handler.dispatchMessage(Handler.java:106) at androidx.test.espresso.base.Interrogator.loopAndInterrogate(Interrogator.java:10) at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:7) at androidx.test.espresso.base.UiControllerImpl.loopUnt forth issue StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Landroid/graphics/FontFamily;->addFontFromBuffer(Ljava/nio/ByteBuffer;I[Landroid/graphics/fonts/FontVariationAxis;II)Z at android.os.StrictMode.lambda$static$1(StrictMode.java:428) at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2) at java.lang.Class.getDeclaredMethodInternal(Native Method) at java.lang.Class.getPublicMethodRecursive(Class.java:2075) at java.lang.Class.getMethod(Class.java:2063) at java.lang.Class.getMethod(Class.java:1690) at androidx.core.graphics.TypefaceCompatApi26Impl.obtainAddFontFromBufferMethod(TypefaceCompatApi26Impl.java:333) at androidx.core.graphics.TypefaceCompatApi26Impl.(TypefaceCompatApi26Impl.java:86) at androidx.core.graphics.TypefaceCompatApi28Impl.(TypefaceCompatApi28Impl.java:36) at androidx.core.graphics.TypefaceCompat.(TypefaceCompat.java:51) at androidx.core.graphics.TypefaceCompat.create(Unknown Source:0) at androidx.appcompat.widget.AppCompatTextView.setTypeface(AppCompatTextView.java:708) at android.widget.TextView.resolveStyleAndSetTypeface(TextView.java:2037) at android.widget.TextView.setTypefaceFromAttrs(TextView.java:2008) at android.widget.TextView.applyTextAppearance(TextView.java:3640) at android.widget.TextView.(TextView.java:1498) at android.widget.TextView.(TextView.java:869) at androidx.appcompat.widget.AppCompatTextView.(AppCompatTextView.java:100) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:93) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:88) at com.google.android.material.textview.MaterialTextView.(MaterialTextView.java:83) at com.google.android.material.theme.MaterialComponentsViewInflater.createTextView(MaterialComponentsViewInflater.java:61) at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:115) at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1551) at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1602) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:772) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) at android.view.LayoutInflater.rInflate(LayoutInflater.java:863) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.inflate(LayoutInflater.java:515) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at android.view.LayoutInflater.inflate(LayoutInflater.java:374) at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696) at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170) at com.example.bmicalculator.MainActivity.onCreate(MainActivity.kt:27) at android.app.Activity.performCreate(Activity.java:7144) at android.app.Activity.performCreate(Activity.java:7135) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at androidx.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:2) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2931) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3086) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816) at android.os.Handler.dispatchMessage(Handler.java:106) at androidx.test.espresso.base.Interrogator.loopAndInterrogate(Interrogator.java:10) at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:7) at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:1) at androidx.test

dimanche 28 mars 2021

how to creaate widget test for statefulwidget

I have 3 different files/screens (the main, the login and the sign up), where the login and sign up are statefulwidgtes. i would like to perform widget testing in the screens, however, it seems like I can't get the widgets under login and sign up, every time I try I get the message:

Expected: exactly one matching node in the widget tree Actual: _WidgetTypeFinder:<zero widgets with type "ListView" (ignoring offstage widgets)> Which: means none were found but one was expected

Please note that in the example above, the ListView widget actually exist, but isn't being located by the tester.

Here is the code of the main widget

import "package:flutter/material.dart";
import 'package:loginscreen/setup/login.dart';
import 'package:firebase_core/firebase_core.dart';
// void main() => runApp(MyApp());

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(primarySwatch: Colors.blue), home: LoginPage());
  }
}

code for Loginpage:

import 'package:flutter/material.dart';
import './signup.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:loginscreen/pages/home.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';

class LoginPage extends StatefulWidget {
  LoginPage({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => new _State();
}

class _State extends State<LoginPage> {
  TextEditingController nameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  String email;
  String password;
  final _auth = FirebaseAuth.instance;
  bool showSpinner = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Sign In'),
      ),
      body: ModalProgressHUD(
        inAsyncCall: showSpinner,
        child: Padding(
          padding: EdgeInsets.all(10),
          child: ListView(
            children: <Widget>[
              Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.all(10),
                  child: Text(
                    'Firebase Authentication',
                    style: TextStyle(
                        color: Colors.blue,
                        fontWeight: FontWeight.w500,
                        fontSize: 30),
                  )),
              Container(
                padding: EdgeInsets.all(10),
                child: TextField(
                  keyboardType: TextInputType.emailAddress,
                  onChanged: (value) {
                    email = value;
                  },
                  controller: nameController,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Email Address',
                  ),
                ),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
                child: TextField(
                  onChanged: (value) {
                    password = value;
                  },
                  obscureText: true,
                  controller: passwordController,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Password',
                  ),
                ),
              ),
              TextButton(
                onPressed: () {
                  //forgot password screen
                },
                // textColor: Colors.blue,
                child: Text('Forgot Password'),
              ),
              Container(
                height: 50,
                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                // ignore: deprecated_member_use
                child: RaisedButton(
                  textColor: Colors.white,
                  color: Colors.blue,
                  child: Text('Login'),
                  onPressed: () async {
                    setState(() {
                      showSpinner = true;
                    });
                    try {
                      await _auth.signInWithEmailAndPassword(
                          email: email, password: password);
                      setState(() {
                        showSpinner = true;
                      });
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => WelcomePage(),
                        ),
                      );
                    } on FirebaseAuthException catch (e) {
                      if (e.code == 'user-not-found') {
                        print('No user found for that email.');
                      } else if (e.code == 'wrong-password') {
                        print('Wrong password provided for that user.');
                      }
                    }
                  },
                ),
              ),
              Container(
                  child: Row(
                children: [
                  Text('Don\'t not have account?'),
                  // ignore: deprecated_member_use
                  FlatButton(
                    textColor: Colors.blue,
                    child: Text(
                      'Sign Up',
                      style: TextStyle(fontSize: 20),
                    ),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => SignupPage()),
                      );
                    },
                  )
                ],
                mainAxisAlignment: MainAxisAlignment.center,
              ))
            ],
          ),
        ),
      ),
    );
  }
}

code for signup page:

import 'package:flutter/material.dart';
import './login.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:loginscreen/pages/home.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';

class SignupPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _State();
}

class _State extends State<SignupPage> {
  TextEditingController nameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  final _auth = FirebaseAuth.instance;
  String email;
  String password;
  String repeatpassword;
  bool showSpinner = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Login Screen App'),
        ),
        body: ModalProgressHUD(
            inAsyncCall: showSpinner,
            child: Padding(
                padding: EdgeInsets.all(10),
                child: ListView(
                  children: <Widget>[
                    Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.all(10),
                        child: Text(
                          'Firebase Authentication',
                          style: TextStyle(
                              color: Colors.blue,
                              fontWeight: FontWeight.w500,
                              fontSize: 30),
                        )),
                    Container(
                      padding: EdgeInsets.all(10),
                      child: TextField(
                        keyboardType: TextInputType.emailAddress,
                        onChanged: (value) {
                          email = value;
                        },
                        controller: nameController,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(),
                          labelText: 'Email Address',
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
                      child: TextField(
                        onChanged: (value) {
                          password = value;
                        },
                        obscureText: true,
                        controller: passwordController,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(),
                          labelText: 'Password (must be at least 6 characters)',
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
                      child: TextField(
                        onChanged: (value) {
                          repeatpassword = value;
                        },
                        obscureText: true,
                        controller: passwordController,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(),
                          labelText: 'Repeat Password',
                        ),
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        //forgot password screen
                      },
                      // textColor: Colors.blue,
                      child: Text('Forgot Password'),
                    ),
                    Container(
                      height: 50,
                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: ElevatedButton(
                        // textColor: Colors.white,
                        // color: Colors.blue,
                        child: Text('Sign Up'),
                        onPressed: () async {
                          setState(() {
                            showSpinner = true;
                          });
                          try {
                            // UserCredential userCredential =
                            await _auth.createUserWithEmailAndPassword(
                                email: email, password: password);
                            setState(() {
                              showSpinner = false;
                            });
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => WelcomePage(),
                              ),
                            );
                          } on FirebaseAuthException catch (e) {
                            if (e.code == 'weak-password') {
                              print('The password provided is too weak.');
                            } else if (e.code == 'email-already-in-use') {
                              print(
                                  'The account already exists for that email.');
                            }
                          } catch (e) {
                            print(e);
                          }
                        },
                      ),
                    ),
                    Container(
                        child: Row(
                      children: <Widget>[
                        Text('Already have an account?'),
                        // ignore: deprecated_member_use
                        FlatButton(
                          textColor: Colors.blue,
                          child: Text(
                            'Sign in',
                            style: TextStyle(fontSize: 20),
                          ),
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => LoginPage()),
                            );
                          },
                        )
                      ],
                      mainAxisAlignment: MainAxisAlignment.center,
                    ))
                  ],
                ))));
  }
}

login page widget test (this is not working):

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:loginscreen/setup/login.dart';

void main() {
  testWidgets(' ', (WidgetTester tester) async {
    // add it to the widget tester
    await tester.pumpWidget(LoginPage());

    expect(find.byType(Text), findsOneWidget);
    
  });
}

so my question is, how can I test the login and sign up stateful widgets? how do I get the widgets inside these screens?flu

How to compare values (aliases) in Cypress.io?

I have two views on my application, a grid with just profile pictures and a name overlayed.

The first view, from the grid, I have saved to an alias called username1

I then want to click on the profile and then make sure that the name property that shows up is the same as the grid view. I have that name saved as a variable profile1Username.

grabbing username from grid view

cy.get('[data-cy=grid-profile-name]')
      .first()
      .then(($name) => {
        return $name.text()
      })
      .as('username1')
    cy.get('@username1').then(($name) => {
      cy.log($name)
    })

clicking on the profile

cy.get('[data-cy=profile-tile]').first().click()
    cy.get('[data-cy=text-display-name]')
      .then(($name) => {
        return $name.text()
      })
      .as('profile1Username')
 cy.get('@profile1Username').then(($name) => {
      cy.log($name)

cy.get('@profile1Username').should('have.value', '@username1')

This should call just checks to see if the profile1username = the string of 'username1' and NOT the value.

What am I doing wrong here? I am able to log the values correctly, but then I am apparently not being able to get the values in the .should() I use at the end to compare.

Cheers!

Output needed for following steps in Yocto

I need a description for each testing steps and results on each of them Here are the steps

  1. Install a Yocto-addon that modifies the Yocto configuration to add the required components to the environment

  2.  After installation, the Linux image needs to be completely rebuilt including the kernel
    
  3.  The resulting image after installation includes Application Whitelist enforcement
    
  4.  The Yocto-addon also adds a policy creation step that adds all image programs (executables libraries and scripts) to the whitelist automatically.
    
  5.  After the built image is flashed to a device, only the programs detected during the build are allowed to run.
    
  6.  Whitelisting is done when a program starts and decides if it is allowed or not.
    
  7.  The product also whitelists shell-scripts
    

Online servers for testing web forms [closed]

Please where can I test a simple form online using my Gmail account.

I use Xampp. But find it difficult to use I thought using an online server might be faster and easier to test my form.

Xamarin UI Testing on Visual Studio Community 2019

I've been trying for hours trying to get the Xamarin UI Testing project type to show up by installing various visual studio packages, as well as attempting to add the Xamarin.UITesting nuget package to my existing unit testing project. I've consulted dozens of guides on the subject and read bug reports and stack overflow questions.

I can't find it definitively stated anywhere, but I think I've finally decided that I need the enterprise version of Visual Studio. Can anyone just confirm that for me?

Django python problem finding h1 element and title

I am reading the book "TDD in practice" and I follow it, however, when I want to check functional tests, I get this error:

======================================================================
ERROR: test_title (__main__.NewvisitorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File 
"C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\superlists\functional_tests.py", 
line 19, in test_title
header_text = self.browser.find_element_by_tag_name('h1').text
File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- 
packages\selenium\webdriver\remote\webdriver.py", line 530, in find_e
lement_by_tag_name
return self.find_element(by=By.TAG_NAME, value=name)
File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- 
packages\selenium\webdriver\remote\webdriver.py", line 976, in find_e
lement
return self.execute(Command.FIND_ELEMENT, {
File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- 
packages\selenium\webdriver\remote\webdriver.py", line 321, in execut
e
self.error_handler.check_response(response)
File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- 
packages\selenium\webdriver\remote\errorhandler.py", line 242, in che
ck_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate 
element: {"method":"css selector","selector":"h1"}
(Session info: chrome=89.0.4389.90)


----------------------------------------------------------------------
Ran 2 tests in 11.605s

FAILED (errors=1)

I understand that the h1 tag is a problem, but I don't understand why it can't find it.

functional_tests.py

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest

class NewvisitorTest(unittest.TestCase):

    def setUp(self):
        self.browser = webdriver.Chrome()
        self.browser.implicitly_wait(4)

    def tearDown(self):
        self.browser.quit()

    def test_can_start_a_list_retrieve_it_later(self):
        self.browser.get('http://localhost:8000')

    def test_title(self):
        self.assertIn('', self.browser.title)
        header_text = self.browser.find_element_by_tag_name('h1').text
        self.assertIn('Listy', header_text)

        inputbox = self.browser.find_element_by_id('id_new_item')
        self.assertEqual(inputbox.get_attribute('placeholder'),'Wpisz rzecz do zrobienia')

        inputbox.send_keys('Kupić pawie pióra')
        inputbox.send_keys(Keys.ENTER)
        table = self.browser.find_element_by_id('id_list_table')
        rows = table.find_elements_by_tag_name('tr')
        self.assertTrue(any(row.text == '1: Kupić pawie pióra' for row in rows))
        self.fail('Zakończenie testu!')

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

home.html

<html>
<head>
    <meta charset="UTF-8">
    <title>Listy rzeczy do zrobienia</title>
</head>
<body>
    <h1>Twoja lista rzeczy do zrobienia</h1>
    <input id="id_new_item" />
</body>
</html>
  1. While I will add an entry to the test:

    self.assertIn('Listy', self.browser.title)

Wyskakuję błąd:

self.assertIn('Listy', self.browser.title)
AssertionError: 'Listy' not found in ''

I understand that self.browser.title doesn't refer to

<title>Listy ...</title> 

Can we use functions to arrange unit test so that we can reuse it?

I have read several posts online that unit tests should be independent.

However, this significantly increases the amount of code and we have a lot of repetition.

This is an illustration:

describe('Magic Calculator', () => {
    let param1:any;
    let param2:any;
    let param3:any;
    function arrangeDefault () {
        param1 = {
            foo1: 1, foo2: 2, foo3: 3, // ... 
        }
        param2 = {
            foo1: 1, foo2: 2, foo3: 3, // ... 
        }
        param3 = {
            foo1: 1, foo2: 2, foo3: 3, // ... 
        }
    }

    it('should work for most common case', () => {
        arrangeDefault();
        const result = MagicCalculator(param1, param2, param3)
        expect(result.value).equal(200);
    })
    it('should work for edge case 1', () => {
        arrangeDefault();
        param1.foo1 = -1
        const result = MagicCalculator(param1, param2, param3)
        expect(result.value).equal(500);
    })

    it('should work for edge case 2', () => {
        arrangeDefault();
        param1.foo1 = 0
        const result = MagicCalculator(param1, param2, param3)
        expect(result.value).equal(503);
    })

    it('should work for edge case 3', () => {
        arrangeDefault();
        param1.foo1 = null
        const result = MagicCalculator(param1, param2, param3)
        expect(result.value).equal(401);
    })

})

As you noticed, every test case uses a common arrange function arrangeDefault. This decreases significantly the amount of code required, and it is much cleaner at the time of the writing. But several months later, one of these test case fails, it takes so much time to understand why the test case is failing. That's because we have to do a lot of declaration finding, trying to understand what changed the states of the param, understanding how the code fits together, until we can know what the bug is.

So if I follow the advice of the posts that I read online, the test code should look like this:

describe('Magic Calculator', () => {


    it('should work for most common case', () => {
        let param1 = {
            foo1: 1, foo2: 2, foo3: 3, // ...
        }
        let param2 = {
            foo1: 1, foo2: 2, foo3: 3, // ...
        }
        let param3 = {
            foo1: 1, foo2: 2, foo3: 3, // ...
        }
        const result = MagicCalculator(param1, param2, param3)
        expect(result.value).equal(200);
    })
    it('should work for edge case 1', () => {
        let param1 = {
            foo1: -1, foo2: 2, foo3: 3, // ...
        }
        let param2 = {
            foo1: 1, foo2: 2, foo3: 3, // ...
        }
        let param3 = {
            foo1: 1, foo2: 2, foo3: 3, // ...
        }
        const result = MagicCalculator(param1, param2, param3)
        expect(result.value).equal(500);
    })

    it('should work for edge case 2', () => {
        let param1 = {
            foo1: 0, foo2: 2, foo3: 3, // ...
        }
        let param2 = {
            foo1: 1, foo2: 2, foo3: 3, // ...
        }
        let param3 = {
            foo1: 1, foo2: 2, foo3: 3, // ...
        }
        const result = MagicCalculator(param1, param2, param3)
        expect(result.value).equal(503);
    })

    it('should work for edge case 3', () => {
        let param1 = {
            foo1: null, foo2: 2, foo3: 3, // ...
        }
        let param2 = {
            foo1: 1, foo2: 2, foo3: 3, // ...
        }
        let param3 = {
            foo1: 1, foo2: 2, foo3: 3, // ...
        }
        const result = MagicCalculator(param1, param2, param3)
        expect(result.value).equal(401);
    })

})

But now we have a lot of repetition, and this is just an illustration, the actual code has way more parameters for the setup. so what is the correct way to do things ? Where is the root cause of my problem ?