/*
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.  The ASF licenses this file to you under the Apache License, Version
 * 2.0 (the "License"); you may not use this file except in compliance with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
 * and limitations under the License.
 */

package org.apache.storm.security.auth;

import java.security.AccessControlException;
import java.util.HashMap;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;


import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;

public class X509CertPrincipalToLocalTest {
    private static X509CertPrincipalToLocal x509CertPrincipalToLocal;
    @BeforeAll
    static public void setup() {
        x509CertPrincipalToLocal = new X509CertPrincipalToLocal();
        x509CertPrincipalToLocal.prepare(new HashMap<String, Object>() {{
            put(X509CertPrincipalToLocal.X509_CERT_PRINCIPAL_TO_LOCAL_REGEX, "test:test_role\\.uid\\.(.+)");
        }});
    }

    @Test
    public void toLocalTest() {
        assertEquals("xyz", x509CertPrincipalToLocal.toLocal("CN=test:test_role.uid.xyz"));
    }
    @Test
    public void toLocalTestNegative() {
        try {
            x509CertPrincipalToLocal.toLocal("CN=test_not_defined:test_role.uid.xyz");
            fail("Should have got AccessControlException");
        } catch (AccessControlException expectedException) {
            assertEquals("Invalid principal CN=test_not_defined:test_role.uid.xyz",
                    expectedException.getMessage());
        }
    }
}
