Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 5b444b94 authored by Max Loh's avatar Max Loh
Browse files

Aslgen tests

Contains logic for testing as well as a couple of initial tests for HR to OD conversion. More tests will be added later. Also fixed a bug with data type parsing.

Bug: 329902686
Test: JUnit unit tests, verified by running atest
Change-Id: I6103f5f93169f25a430cab16c2d1cb1fc4b89d44
parent 9866018a
Loading
Loading
Loading
Loading
+13 −0
Original line number Diff line number Diff line
@@ -5,6 +5,7 @@ package {
    // to get the below license kinds:
    //   SPDX-license-identifier-Apache-2.0
    default_applicable_licenses: ["frameworks_base_license"],
    default_team: "trendy_team_preload_safety",
}

java_library_host {
@@ -24,3 +25,15 @@ java_binary_host {
        "asllib",
    ],
}

java_test_host {
    name: "aslgen-test",
    srcs: ["src/test/java/**/*.java"],
    exclude_srcs: [
    ],
    java_resource_dirs: ["src/test/resources"],
    static_libs: [
        "aslgen",
        "junit",
    ],
}
+18 −0
Original line number Diff line number Diff line
@@ -22,9 +22,12 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
@@ -78,6 +81,13 @@ public class AndroidSafetyLabel implements AslMarshallable {
        }
    }

    /** Reads a {@link AndroidSafetyLabel} from a String. */
    public static AndroidSafetyLabel readFromString(String in, Format format)
            throws IOException, ParserConfigurationException, SAXException, MalformedXmlException {
        InputStream stream = new ByteArrayInputStream(in.getBytes(StandardCharsets.UTF_8));
        return readFromStream(stream, format);
    }

    /** Write the content of the {@link AndroidSafetyLabel} to a {@link OutputStream}. */
    // TODO(b/329902686): Support outputting human-readable format.
    public void writeToStream(OutputStream out, Format format)
@@ -108,6 +118,14 @@ public class AndroidSafetyLabel implements AslMarshallable {
        transformer.transform(domSource, streamResult);
    }

    /** Get the content of the {@link AndroidSafetyLabel} as String. */
    public String getXmlAsString(Format format)
            throws IOException, ParserConfigurationException, TransformerException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        this.writeToStream(out, format);
        return out.toString(StandardCharsets.UTF_8);
    }

    /** Creates an on-device DOM element from an {@link AndroidSafetyLabel} */
    @Override
    public List<Element> toOdDomElements(Document doc) {
+1 −1
Original line number Diff line number Diff line
@@ -108,7 +108,7 @@ public class XmlUtils {
    public static List<Element> asElementList(NodeList nodeList) {
        List<Element> elementList = new ArrayList<Element>();
        for (int i = 0; i < nodeList.getLength(); i++) {
            var elementAsNode = nodeList.item(0);
            var elementAsNode = nodeList.item(i);
            if (elementAsNode instanceof Element) {
                elementList.add(((Element) elementAsNode));
            }
+26 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed 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 com.android.aslgen;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
    AslgenTests.class,
})
public class AllTests {}
+105 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed 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 com.android.aslgen;

import static org.junit.Assert.assertEquals;

import com.android.asllib.AndroidSafetyLabel;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

@RunWith(JUnit4.class)
public class AslgenTests {
    private static final String VALID_MAPPINGS_PATH = "com/android/aslgen/validmappings";
    private static final List<String> VALID_MAPPINGS_SUBDIRS = List.of("location", "contacts");
    private static final String HR_XML_FILENAME = "hr.xml";
    private static final String OD_XML_FILENAME = "od.xml";

    /** Logic for setting up tests (empty if not yet needed). */
    public static void main(String[] params) throws Exception {}

    /** Tests valid mappings between HR and OD. */
    @Test
    public void testValidMappings() throws Exception {
        System.out.println("start testing valid mappings.");

        for (String subdir : VALID_MAPPINGS_SUBDIRS) {
            Path hrPath = Paths.get(VALID_MAPPINGS_PATH, subdir, HR_XML_FILENAME);
            Path odPath = Paths.get(VALID_MAPPINGS_PATH, subdir, OD_XML_FILENAME);

            System.out.println("hr path: " + hrPath.toString());
            System.out.println("od path: " + odPath.toString());

            InputStream hrStream =
                    getClass().getClassLoader().getResourceAsStream(hrPath.toString());
            String hrContents = new String(hrStream.readAllBytes(), StandardCharsets.UTF_8);
            InputStream odStream =
                    getClass().getClassLoader().getResourceAsStream(odPath.toString());
            String odContents = new String(odStream.readAllBytes(), StandardCharsets.UTF_8);
            AndroidSafetyLabel asl =
                    AndroidSafetyLabel.readFromString(
                            hrContents, AndroidSafetyLabel.Format.HUMAN_READABLE);
            String out = asl.getXmlAsString(AndroidSafetyLabel.Format.ON_DEVICE);
            System.out.println("out: " + out);

            assertEquals(getFormattedXml(out), getFormattedXml(odContents));
        }
    }

    private static String getFormattedXml(String xmlStr)
            throws ParserConfigurationException, IOException, SAXException, TransformerException {
        InputStream stream = new ByteArrayInputStream(xmlStr.getBytes(StandardCharsets.UTF_8));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document document = factory.newDocumentBuilder().parse(stream);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult(outStream); // out
        DOMSource domSource = new DOMSource(document);
        transformer.transform(domSource, streamResult);

        return outStream.toString(StandardCharsets.UTF_8);
    }
}
Loading