### Question:
UserMapping { public String mapUser(String principal) throws UserMappingException { for (Rule rule : rules) { Optional<String> user = rule.mapUser(principal); if (user.isPresent()) { return user.get(); } } throw new UserMappingException("No user mapping patterns match the principal"); } @VisibleForTesting  UserMapping(List<Rule> rules); static UserMapping createUserMapping(Optional<String> userMappingPattern, Optional<File> userMappingFile); String mapUser(String principal);  }### Answer:
@Test public void testSimplePatternRule() throws Exception { UserMapping userMapping = new UserMapping(ImmutableList.of(new Rule("(.*?)@.*"))); assertEquals(userMapping.mapUser("test@example.com"), "test"); assertThrows(UserMappingException.class, () -> userMapping.mapUser("no at sign")); assertThrows(UserMappingException.class, () -> userMapping.mapUser("@no user string")); }
@Test public void testReplacePatternRule() throws Exception { UserMapping userMapping = new UserMapping(ImmutableList.of(new Rule("(.*?)@.*", "$1 ^ $1", true, KEEP))); assertEquals(userMapping.mapUser("test@example.com"), "test ^ test"); assertThrows(UserMappingException.class, () -> userMapping.mapUser("no at sign")); UserMapping emptyMapping = new UserMapping(ImmutableList.of(new Rule("(.*?)@.*", " ", true, KEEP))); assertThrows(UserMappingException.class, () -> emptyMapping.mapUser("test@example.com")); }
@Test public void testNotAllowedRule() { UserMapping userMapping = new UserMapping(ImmutableList.of(new Rule("(.*?)@.*", "$1", false, KEEP))); assertThrows(UserMappingException.class, () -> userMapping.mapUser("test@example.com")); UserMapping emptyMapping = new UserMapping(ImmutableList.of(new Rule("(.*?)@.*", "", false, KEEP))); assertThrows(UserMappingException.class, () -> emptyMapping.mapUser("test@example.com")); }
@Test public void testMultipleRule() throws Exception { UserMapping userMapping = new UserMapping(ImmutableList.of(new Rule("test@example.com", "", false, KEEP), new Rule("(.*?)@example.com"))); assertEquals(userMapping.mapUser("apple@example.com"), "apple"); assertThrows(UserMappingException.class, () -> userMapping.mapUser("test@example.com")); assertThrows(UserMappingException.class, () -> userMapping.mapUser("apple@other.example.com")); }
@Test public void testLowercaseUsernameRule() throws UserMappingException { UserMapping userMapping = new UserMapping(ImmutableList.of(new Rule("(.*)@EXAMPLE\\.COM", "$1", true, UserMapping.Case.LOWER))); assertEquals(userMapping.mapUser("TEST@EXAMPLE.COM"), "test"); }
@Test public void testUppercaseUsernameRule() throws UserMappingException { UserMapping userMapping = new UserMapping(ImmutableList.of(new Rule("(.*)@example\\.com", "$1", true, UserMapping.Case.UPPER))); assertEquals(userMapping.mapUser("test@example.com"), "TEST"); }