mvysny / karibu-testing

Vaadin Server-Side Browserless Containerless Unit Testing
Apache License 2.0
105 stars 14 forks source link

Changing role during unit test does not work #153

Closed satorstefan closed 1 year ago

satorstefan commented 1 year ago

Hello Martin,

I want to test that the ui shows only the elements which are available based on the user role.

The logout methode from the AAppTest.class removes a role/user from the SecurityContextHolder/SecurityAuthenticatedUser, but that does not affect how karibu interacts with the "ui". This leads to the issue that in a test in which data gets prepared by an admin user, the "not admin" user still sees all the elements he normally should not be able to see.

The work around is to trigger additional navigation. Of course I would like to avoid that. Is there a way to logout in a "stronger" sense?

@Test
    void an_employee_can_only_view_data() {
        //given
        tester.asAdmin();
        login(tester.getLogin(), tester.getPW(), tester.getRoles());

        var threat = createThreatInPool();
        logout();

        //when
        tester.asEmployee();
        login(tester.getLogin(), tester.getPW(), tester.getRoles());

        //this two navigations are only needed so that the ui gets "reopend" and the user role reevaluated
        // which leads to a check of the user role 
        tester.navigate.toSafeguardTable();
        tester.navigate.toThreatTable();

        //then
        checkThatDataCanOnlyBeViewed(threat);
    }

I use the following dependencies:

org.springframework.boot spring-boot-starter-parent 2.7.7 23.2.2 1.3.24 karibu-testing-v10-spring karibu-testing-v23 The logout methode from AppTest class ``` protected void logout() { SecurityContextHolder.getContext().setAuthentication(null); if (VaadinServletRequest.getCurrent() != null) { final MockRequest request = (MockRequest) VaadinServletRequest.getCurrent().getRequest(); request.setUserPrincipalInt(null); request.setUserInRole((principal, role) -> false); } } ```
mvysny commented 1 year ago

I think the problem is that the UI doesn't know that the user has been logged out and needs to be redrawn. You can reload a page to achieve that. This doesn't sound like a bug in Karibu, closing. If you feel it's something Karibu should do instead, please reopen and provide a simple reproducible example project which clearly demonstrates what needs to be done.

satorstefan commented 1 year ago

Thanks Martin,

while that was clear, it was not clear to me how to reload the page.

This can be done with: UI.getCurrent().getPage().reload();

It works now!