PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/core/che-core-typescript-dto-maven-plugin/src/it/java/org/eclipse/che/plugin/typescript/dto/TypeScriptDTOGeneratorMojoITest.java

https://gitlab.com/unofficial-mirrors/eclipse-che
Java | 289 lines | 151 code | 52 blank | 86 comment | 20 complexity | 238dd87a794afbbef226767fd312cd64 MD5 | raw file
  1. /*******************************************************************************
  2. * Copyright (c) 2012-2016 Codenvy, S.A.
  3. * All rights reserved. This program and the accompanying materials
  4. * are made available under the terms of the Eclipse Public License v1.0
  5. * which accompanies this distribution, and is available at
  6. * http://www.eclipse.org/legal/epl-v10.html
  7. *
  8. * Contributors:
  9. * Codenvy, S.A. - initial API and implementation
  10. *******************************************************************************/
  11. package org.eclipse.che.plugin.typescript.dto;
  12. import org.eclipse.che.api.core.util.SystemInfo;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15. import org.testng.annotations.BeforeClass;
  16. import org.testng.annotations.Test;
  17. import java.io.BufferedReader;
  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.io.InputStreamReader;
  21. import java.net.URISyntaxException;
  22. import java.nio.file.Path;
  23. import java.nio.file.StandardCopyOption;
  24. import java.util.ArrayList;
  25. import java.util.List;
  26. import java.util.Optional;
  27. import java.util.stream.Stream;
  28. import static java.util.stream.Collectors.toList;
  29. /**
  30. * Integration test of TypeScriptDTOGeneratorMojo
  31. * It uses docker to launch TypeScript compiler and then launch JavaScript tests to ensure generator has worked correctly
  32. * @author Florent Benoit
  33. */
  34. public class TypeScriptDTOGeneratorMojoITest {
  35. /**
  36. * Logger.
  37. */
  38. private static final Logger LOG = LoggerFactory.getLogger(TypeScriptDTOGeneratorMojoITest.class);
  39. /**
  40. * DTO Generated file
  41. */
  42. private static final String GENERATED_DTO_NAME = "my-typescript-test-module.ts";
  43. /**
  44. * DTO new name
  45. */
  46. private static final String DTO_FILENAME = "dto.ts";
  47. /**
  48. * DTO test name
  49. */
  50. private static final String DTO_SPEC_FILENAME = "dto.spec.ts";
  51. /**
  52. * Target folder of maven.
  53. */
  54. private Path buildDirectory;
  55. /**
  56. * Path to the package.json file used to setup typescript compiler
  57. */
  58. private Path dtoSpecJsonPath;
  59. /**
  60. * Path to the package.json file used to setup typescript compiler
  61. */
  62. private Path packageJsonPath;
  63. /**
  64. * Root directory for our tests
  65. */
  66. private Path rootPath;
  67. /**
  68. * Linux uid.
  69. */
  70. private String linuxUID;
  71. /**
  72. * Linux gid.
  73. */
  74. private String linuxGID;
  75. /**
  76. * Init folders
  77. */
  78. @BeforeClass
  79. public void init() throws URISyntaxException, IOException, InterruptedException {
  80. // setup packages
  81. this.packageJsonPath = new File(TypeScriptDTOGeneratorMojoITest.class.getClassLoader().getResource("package.json").toURI()).toPath();
  82. this.rootPath = this.packageJsonPath.getParent();
  83. // target folder
  84. String buildDirectoryProperty = System.getProperty("buildDirectory");
  85. if (buildDirectoryProperty != null) {
  86. buildDirectory = new File(buildDirectoryProperty).toPath();
  87. } else {
  88. buildDirectory = packageJsonPath.getParent().getParent();
  89. }
  90. LOG.info("Using building directory {0}", buildDirectory);
  91. }
  92. /**
  93. * Generates a docker exec command used to launch node commands
  94. * @return list of command parameters
  95. */
  96. protected List<String> getDockerExec() {
  97. // setup command line
  98. List<String> command = new ArrayList();
  99. command.add("docker");
  100. command.add("run");
  101. command.add("--rm");
  102. command.add("-v");
  103. command.add(rootPath.toString() + ":/usr/src/app");
  104. command.add("-w");
  105. command.add("/usr/src/app");
  106. command.add("node:6");
  107. command.add("/bin/sh");
  108. command.add("-c");
  109. return command;
  110. }
  111. /**
  112. * Get UID of current user (used on Linux)
  113. */
  114. protected String getUid() throws IOException, InterruptedException {
  115. if (this.linuxUID == null) {
  116. // grab user id
  117. ProcessBuilder uidProcessBuilder = new ProcessBuilder("id", "-u");
  118. Process processId = uidProcessBuilder.start();
  119. int resultId = processId.waitFor();
  120. String uid = "";
  121. try (BufferedReader outReader = new BufferedReader(new InputStreamReader(processId.getInputStream()))) {
  122. uid = String.join(System.lineSeparator(), outReader.lines().collect(toList()));
  123. } catch (Exception error) {
  124. throw new IllegalStateException("Unable to get uid" + uid);
  125. }
  126. if (resultId != 0) {
  127. throw new IllegalStateException("Unable to get uid" + uid);
  128. }
  129. try {
  130. Integer.valueOf(uid);
  131. } catch (NumberFormatException e) {
  132. throw new IllegalStateException("The uid is not a number" + uid);
  133. }
  134. this.linuxUID = uid;
  135. }
  136. return this.linuxUID;
  137. }
  138. /**
  139. * Get GID of current user (used on Linux)
  140. */
  141. protected String getGid() throws IOException, InterruptedException {
  142. if (this.linuxGID == null) {
  143. ProcessBuilder gidProcessBuilder = new ProcessBuilder("id", "-g");
  144. Process processGid = gidProcessBuilder.start();
  145. int resultGid = processGid.waitFor();
  146. String gid = "";
  147. try (BufferedReader outReader = new BufferedReader(new InputStreamReader(processGid.getInputStream()))) {
  148. gid = String.join(System.lineSeparator(), outReader.lines().collect(toList()));
  149. } catch (Exception error) {
  150. throw new IllegalStateException("Unable to get gid" + gid);
  151. }
  152. if (resultGid != 0) {
  153. throw new IllegalStateException("Unable to get gid" + gid);
  154. }
  155. try {
  156. Integer.valueOf(gid);
  157. } catch (NumberFormatException e) {
  158. throw new IllegalStateException("The uid is not a number" + gid);
  159. }
  160. this.linuxGID = gid;
  161. }
  162. return this.linuxGID;
  163. }
  164. /**
  165. * Setup typescript compiler by downloading the dependencies
  166. * @throws IOException if unable to start process
  167. * @throws InterruptedException if unable to wait the end of the process
  168. */
  169. @Test(groups = {"tools"})
  170. protected void installTypeScriptCompiler() throws IOException, InterruptedException {
  171. // setup command line
  172. List<String> command = getDockerExec();
  173. // avoid root permissions in generated files
  174. if (SystemInfo.isLinux()) {
  175. command.add(wrapLinuxCommand("npm install"));
  176. } else {
  177. command.add("npm install");
  178. }
  179. // setup typescript compiler
  180. ProcessBuilder processBuilder = new ProcessBuilder().command(command).directory(rootPath.toFile()).redirectErrorStream(true).inheritIO();
  181. Process process = processBuilder.start();
  182. LOG.info("Installing TypeScript compiler in {0}", rootPath);
  183. int resultProcess = process.waitFor();
  184. if (resultProcess != 0) {
  185. throw new IllegalStateException("Install of TypeScript has failed");
  186. }
  187. LOG.info("TypeScript compiler installed.");
  188. }
  189. /**
  190. * Wrap the given command into a command with chown. Also add group/user that match host environment if not exists
  191. * @param command the command to wrap
  192. * @return an updated command with chown applied on it
  193. */
  194. protected String wrapLinuxCommand(String command) throws IOException, InterruptedException {
  195. String setGroup = "export GROUP_NAME=`(getent group " + getGid() + " || (groupadd -g " + getGid() + " user && echo user:x:" + getGid() +")) | cut -d: -f1`";
  196. String setUser = "export USER_NAME=`(getent passwd " + getUid() + " || (useradd -u " + getUid() + " -g ${GROUP_NAME} user && echo user:x:" + getGid() +")) | cut -d: -f1`";
  197. String chownCommand= "chown --silent -R ${USER_NAME}.${GROUP_NAME} /usr/src/app || true";
  198. return setGroup + " && " + setUser + " && " + chownCommand + " && " + command + " && " + chownCommand;
  199. }
  200. /**
  201. * Starts tests by compiling first generated DTO from maven plugin
  202. * @throws IOException if unable to start process
  203. * @throws InterruptedException if unable to wait the end of the process
  204. */
  205. @Test(dependsOnGroups = "tools")
  206. public void compileDTOAndLaunchTests() throws IOException, InterruptedException {
  207. // search DTO
  208. Path p = this.buildDirectory;
  209. final int maxDepth = 10;
  210. Stream<Path> matches = java.nio.file.Files.find(p, maxDepth, (path, basicFileAttributes) -> path.getFileName().toString().equals(GENERATED_DTO_NAME));
  211. // take first
  212. Optional<Path> optionalPath = matches.findFirst();
  213. if (!optionalPath.isPresent()) {
  214. throw new IllegalStateException("Unable to find generated DTO file named '" + GENERATED_DTO_NAME + "'. Check it has been generated first");
  215. }
  216. Path generatedDtoPath = optionalPath.get();
  217. //copy it in test resources folder where package.json is
  218. java.nio.file.Files.copy(generatedDtoPath, this.rootPath.resolve(DTO_FILENAME), StandardCopyOption.REPLACE_EXISTING);
  219. // setup command line
  220. List<String> command = getDockerExec();
  221. // avoid root permissions in generated files
  222. if (SystemInfo.isLinux()) {
  223. command.add(wrapLinuxCommand("npm test"));
  224. } else {
  225. command.add("npm test");
  226. }
  227. // setup typescript compiler
  228. ProcessBuilder processBuilder = new ProcessBuilder().command(command).directory(rootPath.toFile()).redirectErrorStream(true).inheritIO();
  229. Process process = processBuilder.start();
  230. LOG.info("Starting TypeScript tests...");
  231. int resultProcess = process.waitFor();
  232. if (resultProcess != 0) {
  233. throw new IllegalStateException("DTO has failed to compile");
  234. }
  235. LOG.info("TypeScript tests OK");
  236. }
  237. }