From cf833a5c60eeb0ad3f3f0a5ffd4f0005922dc1c9 Mon Sep 17 00:00:00 2001 From: Gayal Dassanayake Date: Tue, 20 Aug 2024 14:20:47 +0530 Subject: [PATCH] Move BuildNewCommandTest to project api --- .../devtools/cmd/BuildNewCommandTest.java | 138 ---------- .../org/ballerina/devtools/cmd/TestUtils.java | 237 ------------------ .../src/test/resources/testng.xml | 2 - .../testerina-object-mocking-test/client.bal | 46 ---- .../testerina-object-mocking-test/service.bal | 61 ----- .../tests/main_test.bal | 118 --------- .../projectapi/BuildNewCommandTest.java | 100 ++++++++ .../org/ballerina/projectapi/TestUtils.java | 6 + 8 files changed, 106 insertions(+), 602 deletions(-) delete mode 100644 devtools-integration-tests/src/test/java/org/ballerina/devtools/cmd/BuildNewCommandTest.java delete mode 100644 devtools-integration-tests/src/test/java/org/ballerina/devtools/cmd/TestUtils.java delete mode 100644 devtools-integration-tests/testerina-object-mocking-test/client.bal delete mode 100644 devtools-integration-tests/testerina-object-mocking-test/service.bal delete mode 100644 devtools-integration-tests/testerina-object-mocking-test/tests/main_test.bal create mode 100644 project-api-tests/src/test/java/org/ballerina/projectapi/BuildNewCommandTest.java diff --git a/devtools-integration-tests/src/test/java/org/ballerina/devtools/cmd/BuildNewCommandTest.java b/devtools-integration-tests/src/test/java/org/ballerina/devtools/cmd/BuildNewCommandTest.java deleted file mode 100644 index f5b3cf488b..0000000000 --- a/devtools-integration-tests/src/test/java/org/ballerina/devtools/cmd/BuildNewCommandTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.ballerina.devtools.cmd; - -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.LinkedList; -import java.util.List; - -import static org.ballerina.devtools.cmd.TestUtils.*; - -/** - * Tests related new command compiling. - */ -public class BuildNewCommandTest { - - public static final String DISTRIBUTION_FILE_NAME = "ballerina-" + MAVEN_VERSION + "-" + CODE_NAME; - public static final String WHITESPACE_PATTERN = "\\s+"; - - private Path tempHomeDirectory; - private Path tempWorkspaceDirectory; - private static Path sourceDirectory; - private ByteArrayOutputStream console; - protected PrintStream printStream; - - @BeforeClass() - public void setUp() throws IOException { - setupDistributions(); - TestUtils.createTempDirectories(); - tempWorkspaceDirectory = Files.createTempDirectory("bal-test-integration-packaging-workspace-"); - } - - @BeforeMethod - public void beforeMethod() { - this.console = new ByteArrayOutputStream(); - this.printStream = new PrintStream(this.console); - } - - @Test(description = "Build package created from new command with default template") - public void testCompilingNewCommandDefaultTempProject() throws IOException { - List args = new LinkedList<>(); - args.add("project_sample"); - Path newOutputPath = TestUtils.executeNew(distributionName, args); - Assert.assertTrue(Files.isDirectory(newOutputPath.resolve("project_sample"))); - Assert.assertTrue(Files.exists(newOutputPath.resolve("project_sample").resolve("Ballerina.toml"))); - - List buildArgs = new LinkedList<>(); - String buildOutput = TestUtils.executeBuild(distributionName, newOutputPath.resolve("project_sample"), buildArgs); - Assert.assertTrue(buildOutput.contains("Compiling source")); - Assert.assertTrue(buildOutput.contains("Generating executable")); - } - - @Test(description = "Build package created from new command with main template") - public void testCompilingNewCommandMainTempProject() throws IOException { - List args = new LinkedList<>(); - args.add("main_sample"); - args.add("-t"); - args.add("main"); - Path newOutputPath = TestUtils.executeNew(distributionName, args); - Assert.assertTrue(Files.isDirectory(newOutputPath.resolve("main_sample"))); - Assert.assertTrue(Files.exists(newOutputPath.resolve("main_sample").resolve("Ballerina.toml"))); - - List buildArgs = new LinkedList<>(); - String buildOutput = TestUtils.executeBuild(distributionName, newOutputPath.resolve("main_sample"), buildArgs); - Assert.assertTrue(buildOutput.contains("Compiling source")); - Assert.assertTrue(buildOutput.contains("Generating executable")); - } - - @Test(description = "Build package created from new command with service template") - public void testCompilingNewCommandServiceTempProject() throws IOException { - List args = new LinkedList<>(); - args.add("service_sample"); - args.add("-t"); - args.add("service"); - Path newOutputPath = TestUtils.executeNew(distributionName, args); - Assert.assertTrue(Files.isDirectory(newOutputPath.resolve("service_sample"))); - Assert.assertTrue(Files.exists(newOutputPath.resolve("service_sample").resolve("Ballerina.toml"))); - - List buildArgs = new LinkedList<>(); - String buildOutput = TestUtils.executeBuild(distributionName, newOutputPath.resolve("service_sample"), buildArgs); - Assert.assertTrue(buildOutput.contains("Compiling source")); - Assert.assertTrue(buildOutput.contains("Generating executable")); - } - - @Test(description = "Build package created from new command with lib template") - public void testCompilingNewCommandLibTempProject() throws IOException { - List args = new LinkedList<>(); - args.add("lib_sample"); - args.add("-t"); - args.add("lib"); - Path newOutputPath = TestUtils.executeNew(distributionName, args); - Assert.assertTrue(Files.isDirectory(newOutputPath.resolve("lib_sample"))); - Assert.assertTrue(Files.exists(newOutputPath.resolve("lib_sample").resolve("Ballerina.toml"))); - - List buildArgs = new LinkedList<>(); - String buildOutput = TestUtils.executeBuild(distributionName, newOutputPath.resolve("lib_sample"), buildArgs); - Assert.assertTrue(buildOutput.contains("Compiling source")); - Assert.assertTrue(buildOutput.contains("Generating executable")); - } - - @AfterClass - private void cleanup() throws IOException { - TestUtils.deleteFiles(); - } - - /** - * Clean and set up distributions. - */ - private void setupDistributions() throws IOException { - TestUtils.cleanDistribution(); - TestUtils.prepareDistribution(DISTRIBUTIONS_DIR.resolve(DISTRIBUTION_FILE_NAME + ".zip")); - } -} diff --git a/devtools-integration-tests/src/test/java/org/ballerina/devtools/cmd/TestUtils.java b/devtools-integration-tests/src/test/java/org/ballerina/devtools/cmd/TestUtils.java deleted file mode 100644 index 31070d31be..0000000000 --- a/devtools-integration-tests/src/test/java/org/ballerina/devtools/cmd/TestUtils.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.ballerina.devtools.cmd; - -import net.lingala.zip4j.ZipFile; -import net.lingala.zip4j.exception.ZipException; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringUtils; -import org.testng.Assert; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class TestUtils { - private TestUtils() { - } - - public static final Path DISTRIBUTIONS_DIR = Paths.get(System.getProperty("distributions.dir")); - public static final Path MAVEN_VERSION = Paths.get(System.getProperty("maven.version")); - public static final Path CODE_NAME = Paths.get(System.getProperty("code.name")); - - private static final String BALLERINA_HOME_DIR = "BALLERINA_HOME_DIR"; - private static final String BALLERINA_DEV_CENTRAL = "BALLERINA_DEV_CENTRAL"; - private static final PrintStream OUT = System.out; - private static final Path TARGET_DIR = Paths.get(System.getProperty("target.dir")); - private static final Path TEST_DISTRIBUTION_PATH = TARGET_DIR.resolve("test-distribution"); - - public static String distributionName = "ballerina-" + MAVEN_VERSION + "-" + CODE_NAME; - private static Path sourceDirectory; - private static Path tempHomeDirectory; - private static Map envProperties; - - public static String executeBuild(String distributionName, Path projectDir, List args) throws - IOException { - args.add(0, "build"); - args.add(0, TEST_DISTRIBUTION_PATH.resolve(distributionName).resolve("bin").resolve("bal").toString()); - OUT.println("Executing: " + StringUtils.join(args, ' ')); - ProcessBuilder pb = new ProcessBuilder(args); - pb.directory(projectDir.toFile()); - Process process = pb.start(); - InputStream inputStream = process.getInputStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - String line; - String output = ""; - while ((line = reader.readLine()) != null) { - output += line + "\n"; - } - if (output.isEmpty()) { - inputStream = process.getErrorStream(); - reader = new BufferedReader(new InputStreamReader(inputStream)); - while ((line = reader.readLine()) != null) { - output += line + "\n"; - } - } - return output; - } - - /** - * Execute ballerina build command. - * - * @param distributionName The name of the distribution. - * @param args The arguments to be passed to the build command. - * @return True if build is successful, else false. - * @throws IOException Error executing build command. - * @throws InterruptedException Interrupted error executing build command. - */ - public static Path executeNew(String distributionName, List args) throws - IOException { - args.add(0, "new"); - args.add(0, TEST_DISTRIBUTION_PATH.resolve(distributionName).resolve("bin").resolve("bal").toString()); - OUT.println("Executing: " + StringUtils.join(args, ' ')); - ProcessBuilder pb = new ProcessBuilder(args); - pb.directory(sourceDirectory.toFile()); - Process process = pb.start(); - InputStream inputStream = process.getInputStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - String line; - String output = ""; - while ((line = reader.readLine()) != null) { - output += line + "\n"; - } - if (output.isEmpty()) { - inputStream = process.getErrorStream(); - reader = new BufferedReader(new InputStreamReader(inputStream)); - while ((line = reader.readLine()) != null) { - output += line + "\n"; - } - } - return sourceDirectory; - } - - /** - * Creates temporary directories. - * - * @throws ZipException Error occurred when extracting. - */ - public static void createTempDirectories() throws IOException { - sourceDirectory = Files.createTempDirectory("bal-test-integration-packaging-workspace-"); - envProperties = addEnvVariables(getEnvVariables()); - tempHomeDirectory = Files.createTempDirectory("bal-test-integration-packaging-home-"); - createSettingToml(tempHomeDirectory); - } - - /** - * Extracts a distribution to a temporary directory. - * - * @param distributionZipPath Path to the distribution. - * @throws ZipException Error occurred when extracting. - */ - public static void prepareDistribution(Path distributionZipPath) throws ZipException { - OUT.println("Extracting: " + distributionZipPath.normalize()); - ZipFile zipFile = new ZipFile(distributionZipPath.toFile()); - zipFile.extractAll(TEST_DISTRIBUTION_PATH.toAbsolutePath().toString()); - } - - /** - * Delete the temporary directory used to extract distributions. - * - * @throws IOException If temporary directory does not exists. - */ - public static void cleanDistribution() throws IOException { - FileUtils.deleteDirectory(TEST_DISTRIBUTION_PATH.toFile()); - } - - /** - * Create Settings.toml inside the home repository. - * - * @param dirPath Path to directory for creating settings.toml. - * @throws IOException i/o exception when writing to file. - */ - static void createSettingToml(Path dirPath) throws IOException { - String content = "[central]\n accesstoken = \"" + getToken() + "\""; - Files.write(dirPath.resolve("Settings.toml"), content.getBytes(), StandardOpenOption.CREATE, - StandardOpenOption.TRUNCATE_EXISTING); - } - - /** - * Get token of ballerina-central-bot required to push the module. - * - * @return token required to push the module. - */ - private static String getToken() { - // staging and dev both has the same access token - return System.getenv("devCentralToken"); - } - - /** - * Get environment variables and add ballerina_home as a env variable the tmp directory. - * - * @return env directory variable array - */ - static Map getEnvVariables() { - Map envVarMap = System.getenv(); - Map retMap = new HashMap<>(); - envVarMap.forEach(retMap::put); - return retMap; - } - - /** - * Delete files inside directories. - * - * @throws IOException throw an exception if an issue occurs - */ - static void deleteFiles() throws IOException { - if (sourceDirectory == null && tempHomeDirectory == null) { - return; - } - if (sourceDirectory != null) { - Files.walk(sourceDirectory).sorted(Comparator.reverseOrder()).forEach(path -> { - try { - Files.delete(path); - } catch (IOException e) { - Assert.fail(e.getMessage(), e); - } - }); - } - if (tempHomeDirectory != null) { - Files.walk(tempHomeDirectory).sorted(Comparator.reverseOrder()).forEach(path -> { - try { - Files.delete(path); - } catch (IOException e) { - Assert.fail(e.getMessage(), e); - } - }); - } - } - - /** - * Get environment variables and add ballerina_home as a env variable the tmp directory. - * - * @return env directory variable array - */ - public static Map addEnvVariables(Map envVariables) throws IOException { - Path tempHomeDirectory = Files.createTempDirectory("bal-test-integration-packaging-home-"); - envVariables.put(BALLERINA_HOME_DIR, tempHomeDirectory.toString()); - envVariables.put(BALLERINA_DEV_CENTRAL, "true"); - return envVariables; - } - - /** - * Get executable jar path. - * - * @param projectPath project path - * @param pkgName package name - * @return executable jar path - */ - static Path getExecutableJarPath(Path projectPath, String pkgName) { - return projectPath.resolve("target").resolve("bin").resolve(pkgName + ".jar"); - } -} diff --git a/devtools-integration-tests/src/test/resources/testng.xml b/devtools-integration-tests/src/test/resources/testng.xml index be5055e339..4e1d336aa5 100644 --- a/devtools-integration-tests/src/test/resources/testng.xml +++ b/devtools-integration-tests/src/test/resources/testng.xml @@ -22,8 +22,6 @@ - - diff --git a/devtools-integration-tests/testerina-object-mocking-test/client.bal b/devtools-integration-tests/testerina-object-mocking-test/client.bal deleted file mode 100644 index 2f05b7bed7..0000000000 --- a/devtools-integration-tests/testerina-object-mocking-test/client.bal +++ /dev/null @@ -1,46 +0,0 @@ -import ballerina/http; - -http:Client orderManagementClient = checkpanic new ("http://localhost:9117/ordermgt"); - -json responsePayload = {}; - -public function findOrder(string orderId) returns (json) { - http:Response|error response = orderManagementClient->get("/order/" + orderId); - - if (response is http:Response) { - return handleResponse(response); - } else { - return {"Error": "Server error"}; - } -} - -public function addOrder(json orderPayload) returns (json) { - - json|error IDJson = orderPayload.Order.ID; - if (IDJson is json) { - string ID = IDJson.toString(); - json foundOrder = findOrder(ID); - if (foundOrder == {"Error": "Order : " + ID + " cannot be found."}) { - http:Response|error response = orderManagementClient->post("/order", orderPayload); - if (response is http:Response) { - return handleResponse(response); - } else { - return "Server error"; - } - } else { - return "Order with same ID already exists"; - } - } else { - return "Server error"; - } -} - -function handleResponse(http:Response response) returns (json) { - var jsonPayload = response.getJsonPayload(); - - if (jsonPayload is json) { - return <@untainted>jsonPayload; - } else { - return {"Error": "Malformed Payload recieved"}; - } -} diff --git a/devtools-integration-tests/testerina-object-mocking-test/service.bal b/devtools-integration-tests/testerina-object-mocking-test/service.bal deleted file mode 100644 index a94545c9bd..0000000000 --- a/devtools-integration-tests/testerina-object-mocking-test/service.bal +++ /dev/null @@ -1,61 +0,0 @@ -import ballerina/http; -import ballerina/log; - -listener http:Listener httpListener = new(9117); - -map ordersMap = {}; - -service /ordermgt on httpListener { - - resource function get 'order/[string orderId](http:Caller caller, http:Request req) { - json? payload = ordersMap[orderId]; - http:Response response = new; - if (payload == null) { - payload = { "Error" : "Order : " + orderId + " cannot be found." }; - } - - response.setJsonPayload(<@untainted> payload); - - var result = caller->respond(response); - if (result is error) { - log:printError("Error sending response"); - } - } - - resource function post 'order(http:Caller caller, http:Request req) { - http:Response response = new; - var orderReq = req.getJsonPayload(); - if (orderReq is json) { - json|error orderIdJson = orderReq.Order.ID; - string orderId = ""; - - if (orderIdJson is json) { - orderId = orderIdJson.toString(); - } else { - log:printError("Error sending response"); - } - - ordersMap[orderId] = <@untainted> orderReq; - - json payload = { status: "Order Created.", orderId: orderId }; - response.setJsonPayload(payload); - - response.statusCode = 201; - - response.setHeader("Location", - "http://localhost:9117/ordermgt/order/" + orderId); - - var result = caller->respond(response); - if (result is error) { - log:printError("Error sending response"); - } - } else { - response.statusCode = 400; - response.setPayload("Invalid payload received"); - var result = caller->respond(response); - if (result is error) { - log:printError("Error sending response"); - } - } - } -} diff --git a/devtools-integration-tests/testerina-object-mocking-test/tests/main_test.bal b/devtools-integration-tests/testerina-object-mocking-test/tests/main_test.bal deleted file mode 100644 index d22197f538..0000000000 --- a/devtools-integration-tests/testerina-object-mocking-test/tests/main_test.bal +++ /dev/null @@ -1,118 +0,0 @@ -import ballerina/test; -import ballerina/http; - -public client class MockHttpClient { - public string url = "http://mockUrl"; - - remote function get(@untainted string path, http:RequestMessage message = (), - http:TargetType targetType = http:Response) returns http:Response | anydata |http:ClientError { - http:Response res = new; - res.statusCode = 500; - return res; - } - - remote function post(@untainted string path, http:RequestMessage message = (), - http:TargetType targetType = http:Response) returns http:Response|anydata|http:ClientError { - http:Response res = new; - res.statusCode = 500; - return res; - } -} - -@test:Config {} -function test_addOrderWithoutMock() { - json orderPayload = { - "Order": { - "ID": "100500", - "Name": "XYZ", - "Description": "Sample order." - } - }; - - json actual = addOrder(orderPayload); - json expected = {"status":"Order Created.","orderId":"100500"}; - - test:assertEquals(actual, expected, "Add order test failed"); - -} - -@test:Config { dependsOn: [test_addOrderWithoutMock]} -function test_addOrderAgain() { - json orderPayload = { - "Order": { - "ID": "100500", - "Name": "XYZ", - "Description": "Sample order." - } - }; - - json actual = addOrder(orderPayload); - json expected = "Order with same ID already exists"; - - test:assertEquals(actual, expected, "Add order test failed"); -} - -// Create mock http client -http:Client mockHttpClient = test:mock(http:Client); - -json getResponse1 = { - "Order": { - "ID": "100", - "Name": "MOCK", - "Description": "Mock Order." - } -}; - -json getResponse2 = { "Error" : "Order : 200 cannot be found." }; - -@test:Config { dependsOn: [test_addOrderWithoutMock]} -function test_findOrder() { - - // Create a Specific response for get - http:Response mockGetResponse = new; - mockGetResponse.setJsonPayload(<@untainted> getResponse1); - test:prepare(mockHttpClient).when("get").thenReturn(mockGetResponse); - - mockGetResponse = new; - mockGetResponse.setJsonPayload(<@untainted> getResponse2); - test:prepare(mockHttpClient).when("get").withArguments("/order/200").thenReturn(mockGetResponse); - - orderManagementClient = mockHttpClient; - - // Try to find a non existing order - json actual = findOrder("100"); - json expected = getResponse1; - test:assertEquals(actual, expected, "Correct mocked response not recieved"); - - actual = findOrder("200"); - expected = getResponse2; - test:assertEquals(actual, expected, "Correct mocked response not recieved"); - -} - - -json postPayload = { - "Order": { - "ID": "200", - "Name": "MOCK", - "Description": "Mock Order." - } -}; - -json postResponse1 = { - status : "Order Created.", - orderId : "200" -}; - -@test:Config { - dependsOn : [test_findOrder] -} -function test_addOrder() { - http:Response mockPostResponse = new; - mockPostResponse.setJsonPayload(<@untainted> postResponse1); - test:prepare(mockHttpClient).when("post").withArguments("/order", postPayload).thenReturn(mockPostResponse); - - json actual = addOrder(postPayload); - json expected = postResponse1; - test:assertEquals(actual, expected, "Correct mocked response not recieved"); -} diff --git a/project-api-tests/src/test/java/org/ballerina/projectapi/BuildNewCommandTest.java b/project-api-tests/src/test/java/org/ballerina/projectapi/BuildNewCommandTest.java new file mode 100644 index 0000000000..ec919adceb --- /dev/null +++ b/project-api-tests/src/test/java/org/ballerina/projectapi/BuildNewCommandTest.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2024, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.ballerina.projectapi; + +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import static org.ballerina.projectapi.CentralTestUtils.createSettingToml; +import static org.ballerina.projectapi.CentralTestUtils.deleteFiles; +import static org.ballerina.projectapi.CentralTestUtils.getEnvVariables; +import static org.ballerina.projectapi.CentralTestUtils.getString; +import static org.ballerina.projectapi.TestUtils.addEnvVariables; +import static org.ballerina.projectapi.TestUtils.executeBuildCommand; +import static org.ballerina.projectapi.TestUtils.executeNewCommand; + +/** + * Tests related new command compiling. + */ +public class BuildNewCommandTest { + public static final Path MAVEN_VERSION = Paths.get(System.getProperty("maven.version")); + public static final Path CODE_NAME = Paths.get(System.getProperty("code.name")); + public static final String DISTRIBUTION_FILE_NAME = "ballerina-" + MAVEN_VERSION + "-" + CODE_NAME; + + private Path tempHomeDirectory; + private Path tempWorkspaceDirectory; + Map envProperties; + + @BeforeClass() + public void setUp() throws IOException { + TestUtils.setupDistributions(); + tempHomeDirectory = Files.createTempDirectory("bal-test-integration-packaging-home-"); + tempWorkspaceDirectory = Files.createTempDirectory("bal-test-integration-packaging-workspace-"); + createSettingToml(tempHomeDirectory); + envProperties = addEnvVariables(getEnvVariables(), tempHomeDirectory); + } + + @DataProvider(name = "data-provider") + public String[][] createProjectTypeData() { + return new String[][] { + {"project_sample", null}, // default template + {"main_sample", "main"}, + {"service_sample", "service"}, + {"lib_sample", "lib"} + }; + } + + @Test(description = "Build package created from new command with default template", dataProvider = "data-provider") + public void testCompilingNewCommandProject(String projectName, String template) + throws IOException, InterruptedException { + List args = new LinkedList<>(); + args.add(projectName); + if (template != null) { + args.add("-t"); + args.add(template); + } + executeNewCommand(DISTRIBUTION_FILE_NAME, tempWorkspaceDirectory, args, envProperties); + Path projectPath = tempWorkspaceDirectory.resolve(projectName); + Assert.assertTrue(Files.isDirectory(projectPath)); + Assert.assertTrue(Files.exists(projectPath.resolve("Ballerina.toml"))); + + List buildArgs = new LinkedList<>(); + Process build = executeBuildCommand(DISTRIBUTION_FILE_NAME, projectPath, buildArgs, envProperties); + String buildOutput = getString(build.getInputStream()); + Assert.assertTrue(buildOutput.contains("Compiling source")); + Assert.assertTrue(buildOutput.contains("Generating executable")); + } + + @AfterClass + private void cleanup() throws IOException { + deleteFiles(tempHomeDirectory); + deleteFiles(tempWorkspaceDirectory); + } +} diff --git a/project-api-tests/src/test/java/org/ballerina/projectapi/TestUtils.java b/project-api-tests/src/test/java/org/ballerina/projectapi/TestUtils.java index 8f9c047dba..67cc0ef516 100644 --- a/project-api-tests/src/test/java/org/ballerina/projectapi/TestUtils.java +++ b/project-api-tests/src/test/java/org/ballerina/projectapi/TestUtils.java @@ -118,6 +118,12 @@ public static Process executeHelpCommand(String distributionName, Path sourceDir return executeCommand("help", distributionName, sourceDirectory, args, envProperties); } + public static Process executeNewCommand(String distributionName, Path sourceDirectory, + List args, Map envProperties) + throws IOException, InterruptedException { + return executeCommand("new", distributionName, sourceDirectory, args, envProperties); + } + /** * Clean and setup the distribution. *