update junit test classes and there dependencies

This commit is contained in:
Florian 2021-10-11 12:38:37 +02:00 committed by arnaudroques
parent 221af78afc
commit 8d5be87f03
20 changed files with 700 additions and 469 deletions

22
pom.xml
View File

@ -84,7 +84,7 @@
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.14.1</version> <version>2.14.1</version>
<configuration> <configuration>
<skipTests>true</skipTests> <skipTests>${skipTests}</skipTests>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
@ -174,6 +174,7 @@
<maven.build.timestamp.format>yyyyMMdd-HHmm <maven.build.timestamp.format>yyyyMMdd-HHmm
</maven.build.timestamp.format> </maven.build.timestamp.format>
<timestamp>${maven.build.timestamp}</timestamp> <timestamp>${maven.build.timestamp}</timestamp>
<skipTests>true</skipTests>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
@ -191,11 +192,6 @@
<artifactId>codemirror</artifactId> <artifactId>codemirror</artifactId>
<version>3.21</version> <version>3.21</version>
</dependency> </dependency>
<dependency>
<groupId>HTTPClient</groupId>
<artifactId>HTTPClient</artifactId>
<version>0.3-3</version>
</dependency>
<dependency> <dependency>
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId> <artifactId>servlet-api</artifactId>
@ -205,19 +201,13 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.13.1</version> <version>4.13.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>httpunit</groupId> <groupId>net.sourceforge.htmlunit</groupId>
<artifactId>httpunit</artifactId> <artifactId>htmlunit</artifactId>
<version>1.7</version> <version>2.53.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>rhino</groupId>
<artifactId>js</artifactId>
<version>1.7R2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -23,23 +23,19 @@
*/ */
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import HTTPClient.CookieModule;
import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.ModuleException;
import HTTPClient.ParseException;
import net.sourceforge.plantuml.FileFormat; import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption; import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.SourceStringReader; import net.sourceforge.plantuml.SourceStringReader;
@ -52,54 +48,50 @@ import net.sourceforge.plantuml.SourceStringReader;
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class OldProxyServlet extends HttpServlet { public class OldProxyServlet extends HttpServlet {
private static final Pattern PROXY_PATTERN = Pattern.compile("/\\w+/proxy/((\\d+)/)?((\\w+)/)?(http://.*)"); private static final Pattern PROXY_PATTERN = Pattern.compile("/\\w+/proxy/((\\d+)/)?((\\w+)/)?(https?://.*)");
private String format; private String format;
@Override @Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
final String uri = request.getRequestURI(); final String uri = request.getRequestURI();
// Check if the src URL is valid
Matcher proxyMatcher = PROXY_PATTERN.matcher(uri); Matcher proxyMatcher = PROXY_PATTERN.matcher(uri);
if (proxyMatcher.matches()) { if (!proxyMatcher.matches()) {
String num = proxyMatcher.group(2); // Optional number of the diagram source // Bad URI format.
format = proxyMatcher.group(4); // Expected format of the generated diagram response.setStatus(400);
String sourceURL = proxyMatcher.group(5); return;
handleImageProxy(response, num, sourceURL);
} else {
request.setAttribute("net.sourceforge.plantuml.servlet.decoded", "ERROR Invalid proxy syntax : " + uri);
request.removeAttribute("net.sourceforge.plantuml.servlet.encoded");
// forward to index.jsp
RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
} }
String num = proxyMatcher.group(2); // Optional number of the diagram source
format = proxyMatcher.group(4); // Expected format of the generated diagram
String sourceURL = proxyMatcher.group(5);
handleImageProxy(response, num, sourceURL);
} }
private void handleImageProxy(HttpServletResponse response, String num, String source) throws IOException { private void handleImageProxy(HttpServletResponse response, String num, String source) throws IOException {
SourceStringReader reader = new SourceStringReader(getSource(source)); SourceStringReader reader = new SourceStringReader(getSource(source));
int n = num == null ? 0 : Integer.parseInt(num); int n = num == null ? 0 : Integer.parseInt(num);
reader.generateImage(response.getOutputStream(), n, new FileFormatOption(getOutputFormat(), false)); FileFormat fileFormat = getOutputFormat();
response.addHeader("Content-Type", fileFormat.getMimeType());
reader.outputImage(response.getOutputStream(), n, new FileFormatOption(fileFormat, false));
} }
private String getSource(String uri) throws IOException { private String getSource(final String uri) throws IOException {
CookieModule.setCookiePolicyHandler(null);
final Pattern p = Pattern.compile("http://[^/]+(/?.*)");
final Matcher m = p.matcher(uri);
if (m.find() == false) {
throw new IOException(uri);
}
final URL url = new URL(uri); final URL url = new URL(uri);
final HTTPConnection httpConnection = new HTTPConnection(url); try (
try { InputStream responseStream = url.openStream();
final HTTPResponse resp = httpConnection.Get(m.group(1)); InputStreamReader isr = new InputStreamReader(responseStream);
return resp.getText(); BufferedReader br = new BufferedReader(isr);
} catch (ModuleException e) { ) {
throw new IOException(e.toString()); String line;
} catch (ParseException e) { StringBuffer sb = new StringBuffer();
throw new IOException(e.toString()); while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
return sb.toString().trim();
} }
} }

View File

@ -76,6 +76,7 @@ public class ProxyServlet extends HttpServlet {
srcUrl = new URL(source); srcUrl = new URL(source);
} catch (MalformedURLException mue) { } catch (MalformedURLException mue) {
mue.printStackTrace(); mue.printStackTrace();
response.setStatus(400);
return; return;
} }

View File

@ -33,7 +33,7 @@
<!-- <script src="mode/plantuml.js"></script> --> <!-- <script src="mode/plantuml.js"></script> -->
<script> <script>
window.onload = function() { window.onload = function() {
var myCodeMirror = CodeMirror.fromTextArea( document.myCodeMirror = CodeMirror.fromTextArea(
document.getElementById("text"), document.getElementById("text"),
{lineNumbers: true} {lineNumbers: true}
); );

View File

@ -1,25 +1,27 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import com.meterware.httpunit.GetMethodWebRequest; import java.io.IOException;
import com.meterware.httpunit.WebConversation; import java.net.URL;
import com.meterware.httpunit.WebRequest; import java.net.URLConnection;
import com.meterware.httpunit.WebResponse;
public class TestAsciiArt extends WebappTestCase { public class TestAsciiArt extends WebappTestCase {
/** /**
* Verifies the generation of the ascii art for the Bob -> Alice sample * Verifies the generation of the ascii art for the Bob -> Alice sample
*/ */
public void testSimpleSequenceDiagram() throws Exception { public void testSimpleSequenceDiagram() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/txt/" + TestUtils.SEQBOB);
WebRequest request = new GetMethodWebRequest(getServerUrl() + "txt/" + TestUtils.SEQBOB); final URLConnection conn = url.openConnection();
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not TEXT PLAIN", "text/plain", response.getContentType()); assertEquals(
assertEquals("Response character set is not UTF-8", "UTF-8", response.getCharacterSet()); "Response content type is not TEXT PLAIN or UTF-8",
"text/plain;charset=utf-8",
conn.getContentType().toLowerCase()
);
// Get the content and verify its size // Get the content and verify its size
String diagram = response.getText(); String diagram = getContentText(conn);
int diagramLen = diagram.length(); int diagramLen = diagram.length();
assertTrue(diagramLen > 200); assertTrue(diagramLen > 200);
assertTrue(diagramLen < 250); assertTrue(diagramLen < 250);

View File

@ -1,24 +1,27 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import com.meterware.httpunit.GetMethodWebRequest; import java.io.IOException;
import com.meterware.httpunit.WebConversation; import java.net.URL;
import com.meterware.httpunit.WebRequest; import java.net.URLConnection;
import com.meterware.httpunit.WebResponse;
public class TestCharset extends WebappTestCase { public class TestCharset extends WebappTestCase {
/** /**
* Verifies the preservation of unicode characters for the "Bob -> Alice : hell‽" sample * Verifies the preservation of unicode characters for the "Bob -> Alice : hell‽" sample
*/ */
public void testUnicodeSupport() throws Exception { public void testUnicodeSupport() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/txt/SyfFKj2rKt3CoKnELR1Io4ZDoNdKi1S0");
WebRequest request = new GetMethodWebRequest(getServerUrl() + "txt/SyfFKj2rKt3CoKnELR1Io4ZDoNdKi1S0"); final URLConnection conn = url.openConnection();
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not TEXT PLAIN", "text/plain", response.getContentType()); assertEquals(
"Response content type is not TEXT PLAIN or UTF-8",
"text/plain;charset=utf-8",
conn.getContentType().toLowerCase()
);
// Get the content and verify that the interrobang unicode character is present // Get the content and verify that the interrobang unicode character is present
String diagram = response.getText(); String diagram = getContentText(conn);
assertTrue("Interrobang unicode character is not preserved", diagram.contains("")); assertTrue("Interrobang unicode character is not preserved", diagram.contains(""));
} }
@ -26,18 +29,22 @@ public class TestCharset extends WebappTestCase {
* Verifies the preservation of unicode characters for the * Verifies the preservation of unicode characters for the
* "participant Bob [[http://www.snow.com/❄]]\nBob -> Alice" sample * "participant Bob [[http://www.snow.com/❄]]\nBob -> Alice" sample
*/ */
public void testUnicodeInCMap() throws Exception { public void testUnicodeInCMap() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(
WebRequest request = new GetMethodWebRequest(getServerUrl() getServerUrl() +
+ "map/AqWiAibCpYn8p2jHSCfFKeYEpYWfAR3IroylBzShpiilrqlEpzL_DBSbDfOB9Azhf-2OavcS2W00"); "/map/AqWiAibCpYn8p2jHSCfFKeYEpYWfAR3IroylBzShpiilrqlEpzL_DBSbDfOB9Azhf-2OavcS2W00"
WebResponse response = conversation.getResource(request); );
final URLConnection conn = url.openConnection();
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not TEXT PLAIN", "text/plain", response.getContentType()); assertEquals(
"Response content type is not TEXT PLAIN or UTF-8",
"text/plain;charset=utf-8",
conn.getContentType().toLowerCase()
);
// Get the content and verify that the snow unicode character is present // Get the content and verify that the snow unicode character is present
String map = response.getText(); String map = getContentText(conn);
assertTrue("Snow unicode character is not preserved", map.contains("")); assertTrue("Snow unicode character is not preserved", map.contains(""));
} }
} }

View File

@ -1,28 +1,32 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import com.meterware.httpunit.GetMethodWebRequest; import java.io.IOException;
import com.meterware.httpunit.WebConversation; import java.net.URL;
import com.meterware.httpunit.WebRequest; import java.net.URLConnection;
import com.meterware.httpunit.WebResponse;
public class TestCheck extends WebappTestCase { public class TestCheck extends WebappTestCase {
/** /**
* Verifies the generation of a syntax check for the following sample: * Verifies the generation of a syntax check for the following sample:
* Bob -> Alice : hello * Bob -> Alice : hello
*/ */
public void testCorrectSequenceDiagram() throws Exception { public void testCorrectSequenceDiagram() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/check/" + TestUtils.SEQBOB);
WebRequest request = new GetMethodWebRequest(getServerUrl() final URLConnection conn = url.openConnection();
+ "check/" + TestUtils.SEQBOB);
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not TEXT PLAIN", "text/plain", response.getContentType()); assertEquals(
assertEquals("Response character set is not UTF-8", "UTF-8", response.getCharacterSet()); "Response content type is not TEXT PLAIN or UTF-8",
"text/plain;charset=utf-8",
conn.getContentType().toLowerCase()
);
// Get the content, check its first characters and verify its size // Get the content, check its first characters and verify its size
String checkResult = response.getText(); String checkResult = getContentText(conn);
assertTrue("Response content is not starting with (2 participants)", assertTrue(
checkResult.startsWith("(2 participants)")); "Response content is not starting with (2 participants)",
checkResult.startsWith("(2 participants)")
);
int checkLen = checkResult.length(); int checkLen = checkResult.length();
assertTrue(checkLen > 1); assertTrue(checkLen > 1);
assertTrue(checkLen < 100); assertTrue(checkLen < 100);
@ -32,12 +36,10 @@ public class TestCheck extends WebappTestCase {
* Check the syntax of an invalid sequence diagram : * Check the syntax of an invalid sequence diagram :
* Bob - * Bob -
*/ */
public void testWrongDiagramSyntax() throws Exception { public void testWrongDiagramSyntax() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/check/SyfFKj050000");
WebRequest request = new GetMethodWebRequest(getServerUrl() + "check/SyfFKj050000");
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
String checkResult = response.getText(); String checkResult = getContentText(url);
assertTrue("Response is not an error", checkResult.startsWith("(Error)")); assertTrue("Response is not an error", checkResult.startsWith("(Error)"));
} }

View File

@ -1,27 +1,30 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import com.meterware.httpunit.GetMethodWebRequest; import java.io.IOException;
import com.meterware.httpunit.WebConversation; import java.net.URL;
import com.meterware.httpunit.WebRequest; import java.net.URLConnection;
import com.meterware.httpunit.WebResponse;
import java.util.Scanner;
public class TestEPS extends WebappTestCase { public class TestEPS extends WebappTestCase {
/** /**
* Verifies the generation of the EPS for the Bob -> Alice sample * Verifies the generation of the EPS for the Bob -> Alice sample
*/ */
public void testSimpleSequenceDiagram() throws Exception { public void testSimpleSequenceDiagram() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/eps/" + TestUtils.SEQBOB);
WebRequest request = new GetMethodWebRequest(getServerUrl() + "eps/" + TestUtils.SEQBOB); final URLConnection conn = url.openConnection();
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not EPS", "application/postscript", response.getContentType()); assertEquals(
"Response content type is not EPS",
"application/postscript",
conn.getContentType().toLowerCase()
);
// Get the content and verify its size // Get the content and verify its size
String diagram = response.getText(); String diagram = getContentText(conn);
int diagramLen = diagram.length(); int diagramLen = diagram.length();
assertTrue(diagramLen > 10000); assertTrue(diagramLen > 10000);
assertTrue(diagramLen < 12000); assertTrue(diagramLen < 12000);
} }
} }

View File

@ -1,155 +1,219 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import com.meterware.httpunit.GetMethodWebRequest; import static org.junit.Assert.assertNotEquals;
import com.meterware.httpunit.HTMLElement;
import com.meterware.httpunit.WebConversation; import java.io.IOException;
import com.meterware.httpunit.WebForm; import java.util.List;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse; import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlImage;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextArea;
public class TestForm extends WebappTestCase { public class TestForm extends WebappTestCase {
/** /**
* Verifies that the welcome page has exactly two form with the Bob --> Alice sample * Verifies that the welcome page has exactly two form with the Bob --> Alice sample
*/ */
public void testWelcomePage() throws Exception { public void testWelcomePage() throws IOException {
WebConversation conversation = new WebConversation(); try (final WebClient webClient = new WebClient()) {
WebRequest request = new GetMethodWebRequest(getServerUrl()); HtmlPage page = webClient.getPage(getServerUrl());
WebResponse response = conversation.getResponse(request); // Analyze response
// Analyze response List<HtmlForm> forms = page.getForms();
WebForm[] forms = response.getForms(); assertEquals(2, forms.size());
assertEquals(2, forms.length); // Ensure the Text field is correct
assertEquals("url", forms[1].getParameterNames()[0]); String text = ((HtmlTextArea)(forms.get(0).getFirstByXPath("//textarea[contains(@name, 'text')]"))).getTextContent();
assertTrue(forms[1].getParameterValue("url").endsWith("/png/" + TestUtils.SEQBOB)); assertEquals("@startuml\nBob -> Alice : hello\n@enduml", text);
// Ensure the generated image is present // Ensure the URL field is correct
assertNotNull(response.getImageWithAltText("PlantUML diagram")); HtmlInput url = forms.get(1).getInputByName("url");
assertNotNull(url);
assertTrue(url.getAttribute("value").endsWith("/png/" + TestUtils.SEQBOB));
// Ensure the generated image is present
HtmlImage img = page.getFirstByXPath("//img[contains(@alt, 'PlantUML diagram')]");
assertNotEquals(0, img.getImageReader().getHeight(0)); // 131
assertNotEquals(0, img.getImageReader().getWidth(0)); // 120
}
} }
/** /**
* Verifies that the version image is generated * Verifies that the version image is generated
*/ */
public void testVersion() throws Exception { public void testVersion() throws IOException {
WebConversation conversation = new WebConversation(); try (final WebClient webClient = new WebClient()) {
// Fill the form and submit it HtmlPage page = webClient.getPage(getServerUrl());
WebRequest request = new GetMethodWebRequest(getServerUrl()); page.initialize();
WebResponse response = conversation.getResponse(request); // Fill the form and submit it
WebForm formUMLText = response.getForms()[0]; page.executeJavaScript("document.myCodeMirror.setValue('version')");
formUMLText.setParameter("text", "version"); HtmlForm form = page.getForms().get(0);
response = formUMLText.submit(); HtmlSubmitInput btn = form.getFirstByXPath("//input[contains(@type, 'submit')]");
// Analyze response page = btn.click();
WebForm[] forms = response.getForms(); // Analyze response
assertEquals(2, forms.length); List<HtmlForm> forms = page.getForms();
// Ensure the Text field is correct assertEquals(2, forms.size());
assertEquals("version", forms[0].getParameterValue("text")); // Ensure the Text field is correct
// Ensure the URL field is correct String text = ((HtmlTextArea)(forms.get(0).getFirstByXPath("//textarea[contains(@name, 'text')]"))).getTextContent();
assertTrue(forms[1].getParameterValue("url").endsWith("/png/" + TestUtils.VERSION)); assertEquals("@startuml\nversion\n@enduml", text);
// Ensure the image is present // Ensure the URL field is correct
assertNotNull(response.getImageWithAltText("PlantUML diagram")); HtmlInput url = forms.get(1).getInputByName("url");
assertNotNull(url);
assertTrue(url.getAttribute("value").endsWith("/png/" + TestUtils.VERSION));
// Ensure the generated image is present
HtmlImage img = page.getFirstByXPath("//img[contains(@alt, 'PlantUML diagram')]");
assertNotEquals(0, img.getImageReader().getHeight(0)); // 186
assertNotEquals(0, img.getImageReader().getWidth(0)); // 519
}
} }
/** /**
* Verifies that when the UML text is empty, no image is generated * Verifies that when the UML text is empty, default page and image is generated
*/ */
public void testEmptyText() throws Exception { public void testEmptyText() throws IOException {
WebConversation conversation = new WebConversation(); try (final WebClient webClient = new WebClient()) {
// Fill the form and submit it HtmlPage page = webClient.getPage(getServerUrl());
WebRequest request = new GetMethodWebRequest(getServerUrl()); page.initialize();
WebResponse response = conversation.getResponse(request); // Fill the form and submit it
WebForm formUMLText = response.getForms()[0]; page.executeJavaScript("document.myCodeMirror.setValue('')");
formUMLText.setParameter("text", ""); HtmlForm form = page.getForms().get(0);
response = formUMLText.submit(); HtmlSubmitInput btn = form.getFirstByXPath("//input[contains(@type, 'submit')]");
// Analyze response page = btn.click();
WebForm[] forms = response.getForms(); // Analyze response
assertEquals(2, forms.length); List<HtmlForm> forms = page.getForms();
// Ensure the Text field is empty assertEquals(2, forms.size());
assertNull(forms[0].getParameterValue("text")); // Ensure the Text field is correct
// Ensure the URL field is empty String text = ((HtmlTextArea)(forms.get(0).getFirstByXPath("//textarea[contains(@name, 'text')]"))).getTextContent();
assertTrue(forms[1].getParameterValue("url").isEmpty()); assertEquals("@startuml\nBob -> Alice : hello\n@enduml", text);
// Ensure there is no image // Ensure the URL field is correct
assertNull(response.getImageWithAltText("PlantUML diagram")); HtmlInput url = forms.get(1).getInputByName("url");
assertNotNull(url);
assertTrue(url.getAttribute("value").endsWith("/png/" + TestUtils.SEQBOB));
// Ensure the generated image is present
HtmlImage img = page.getFirstByXPath("//img[contains(@alt, 'PlantUML diagram')]");
assertNotEquals(0, img.getImageReader().getHeight(0)); // 131
assertNotEquals(0, img.getImageReader().getWidth(0)); // 120
}
} }
/** /**
* Verifies that when the encoded URL is empty, no image is generated * Verifies that when the encoded URL is empty, default page and image is generated
*/ */
public void testEmptyUrl() throws Exception { public void testEmptyUrl() throws IOException {
WebConversation conversation = new WebConversation(); try (final WebClient webClient = new WebClient()) {
// Fill the form and submit it HtmlPage page = webClient.getPage(getServerUrl());
WebRequest request = new GetMethodWebRequest(getServerUrl()); page.initialize();
WebResponse response = conversation.getResponse(request); // Fill the form and submit it
WebForm formUrl = response.getForms()[1]; List<HtmlForm> forms = page.getForms();
formUrl.setParameter("url", ""); HtmlInput url = forms.get(1).getInputByName("url");
response = formUrl.submit(); url.setAttribute("value", "");
// Analyze response HtmlSubmitInput btn = forms.get(1).getFirstByXPath("//input[contains(@type, 'submit')]");
WebForm[] forms = response.getForms(); page = btn.click();
assertEquals(2, forms.length); // Analyze response
// Ensure the Text field is empty forms = page.getForms();
assertNull(forms[0].getParameterValue("text")); assertEquals(2, forms.size());
// Ensure the URL field is empty // Ensure the Text field is correct
assertTrue(forms[1].getParameterValue("url").isEmpty()); String text = ((HtmlTextArea)(forms.get(0).getFirstByXPath("//textarea[contains(@name, 'text')]"))).getTextContent();
// Ensure there is no image assertEquals("@startuml\nBob -> Alice : hello\n@enduml", text);
assertNull(response.getImageWithAltText("PlantUML diagram")); // Ensure the URL field is correct
url = forms.get(1).getInputByName("url");
assertNotNull(url);
assertTrue(url.getAttribute("value").endsWith("/png/" + TestUtils.SEQBOB));
// Ensure the generated image is present
HtmlImage img = page.getFirstByXPath("//img[contains(@alt, 'PlantUML diagram')]");
assertNotEquals(0, img.getImageReader().getHeight(0)); // 131
assertNotEquals(0, img.getImageReader().getWidth(0)); // 120
}
} }
/** /**
* Verifies that a ditaa diagram is generated * Verifies that a ditaa diagram is generated
*/ */
public void testDitaaText() throws Exception { public void testDitaaText() throws IOException {
WebConversation conversation = new WebConversation(); try (final WebClient webClient = new WebClient()) {
// Fill the form and submit it HtmlPage page = webClient.getPage(getServerUrl());
WebRequest request = new GetMethodWebRequest(getServerUrl()); page.initialize();
WebResponse response = conversation.getResponse(request); // Fill the form and submit it
WebForm formDitaaText = response.getForms()[0]; page.executeJavaScript("document.myCodeMirror.setValue(`@startditaa \n*--> \n@endditaa`)");
formDitaaText.setParameter("text", "@startditaa \n*--> \n@endditaa"); HtmlForm form = page.getForms().get(0);
response = formDitaaText.submit(); HtmlSubmitInput btn = form.getFirstByXPath("//input[contains(@type, 'submit')]");
// Analyze response page = btn.click();
WebForm[] forms = response.getForms(); // Analyze response
assertEquals(2, forms.length); List<HtmlForm> forms = page.getForms();
// Ensure the Text field is correct assertEquals(2, forms.size());
assertTrue(forms[0].getParameterValue("text").startsWith("@startditaa")); // Ensure the Text field is correct
// Ensure the URL field is correct String text = ((HtmlTextArea)(forms.get(0).getFirstByXPath("//textarea[contains(@name, 'text')]"))).getTextContent();
assertTrue(forms[1].getParameterValue("url").endsWith("/png/SoWkIImgISaiIKnKuDBIrRLJu798pKi12m00")); assertEquals("@startditaa \n*--> \n@endditaa", text);
// Ensure the image is present // Ensure the URL field is correct
assertNotNull(response.getImageWithAltText("PlantUML diagram")); HtmlInput url = forms.get(1).getInputByName("url");
assertNotNull(url);
assertTrue(url.getAttribute("value").endsWith("/png/SoWkIImgISaiIKnKuDBIrRLJu798pKi12m00"));
// Ensure the generated image is present
HtmlImage img = page.getFirstByXPath("//img[contains(@alt, 'PlantUML diagram')]");
assertNotEquals(0, img.getImageReader().getHeight(0)); // 70
assertNotEquals(0, img.getImageReader().getWidth(0)); // 90
}
} }
/** /**
* Verifies that an image map is produced if the diagram contains a link * Verifies that an image map is produced if the diagram contains a link
*/ */
public void testImageMap() throws Exception { public void testImageMap() throws IOException {
WebConversation conversation = new WebConversation(); try (final WebClient webClient = new WebClient()) {
// Fill the form and submit it HtmlPage page = webClient.getPage(getServerUrl());
WebRequest request = new GetMethodWebRequest(getServerUrl()); page.initialize();
WebResponse response = conversation.getResponse(request); // Fill the form and submit it
WebForm formText = response.getForms()[0]; page.executeJavaScript("document.myCodeMirror.setValue(`@startuml\nBob -> Alice : [[http://yahoo.com]] Hello\n@enduml`)");
formText.setParameter("text", "@startuml \nBob -> Alice : [[http://yahoo.com]] Hello \n@enduml"); HtmlForm form = page.getForms().get(0);
response = formText.submit(); HtmlSubmitInput btn = form.getFirstByXPath("//input[contains(@type, 'submit')]");
// Analyze response page = btn.click();
// Ensure the generated image is present // Analyze response
assertNotNull(response.getImageWithAltText("PlantUML diagram")); List<HtmlForm> forms = page.getForms();
// Ensure the image map is present assertEquals(2, forms.size());
HTMLElement[] maps = response.getElementsByTagName("map"); // Ensure the Text field is correct
assertEquals(1, maps.length); String text = ((HtmlTextArea)(forms.get(0).getFirstByXPath("//textarea[contains(@name, 'text')]"))).getTextContent();
assertEquals("@startuml\nBob -> Alice : [[http://yahoo.com]] Hello\n@enduml", text);
// Ensure the URL field is correct
HtmlInput url = forms.get(1).getInputByName("url");
assertNotNull(url);
assertTrue(url.getAttribute("value").endsWith("/png/SyfFKj2rKt3CoKnELR1IY8xEA2afiDBNhqpCoC_NIyxFZOrLy4ZDoSa70000"));
// Ensure the generated image is present
HtmlImage img = page.getFirstByXPath("//img[contains(@alt, 'PlantUML diagram')]");
assertNotEquals(0, img.getImageReader().getHeight(0)); // 131
assertNotEquals(0, img.getImageReader().getWidth(0)); // 231
// TODO: Ensure the image map is present
//DomElement map = page.getElementById("plantuml_map");
//assertNotNull(map);
//assertEquals(1, map.getChildElementCount());
}
} }
/** /**
* Verifies that when the encoded source is specified as an URL parameter * Verifies that when the encoded source is specified as an URL parameter
* the diagram is displayed and the source is decoded * the diagram is displayed and the source is decoded
*/ */
public void testUrlParameter() throws Exception { public void testUrlParameter() throws IOException {
WebConversation conversation = new WebConversation(); try (final WebClient webClient = new WebClient()) {
// Submit the request with a url parameter // Submit the request with a url parameter
WebRequest request = new GetMethodWebRequest(getServerUrl() + "form?url=" + TestUtils.SEQBOB); HtmlPage page = webClient.getPage(getServerUrl() + "/form?url=" + TestUtils.SEQBOB);
WebResponse response = conversation.getResponse(request); page.initialize();
// Analyze response // Analyze response
WebForm[] forms = response.getForms(); List<HtmlForm> forms = page.getForms();
assertEquals(2, forms.length); assertEquals(2, forms.size());
// Ensure the Text field is filled // Ensure the Text field is correct
assertEquals(forms[0].getParameterValue("text"), "@startuml\nBob -> Alice : hello\n@enduml"); String text = ((HtmlTextArea)(forms.get(0).getFirstByXPath("//textarea[contains(@name, 'text')]"))).getTextContent();
// Ensure the URL field is filled assertEquals("@startuml\nBob -> Alice : hello\n@enduml", text);
assertEquals(forms[1].getParameterValue("url"), getServerUrl() + "png/" + TestUtils.SEQBOB); // Ensure the URL field is correct
// Ensure the image is present HtmlInput url = forms.get(1).getInputByName("url");
assertNotNull(response.getImageWithAltText("PlantUML diagram")); assertNotNull(url);
assertTrue(url.getAttribute("value").endsWith("/png/" + TestUtils.SEQBOB));
// Ensure the generated image is present
HtmlImage img = page.getFirstByXPath("//img[contains(@alt, 'PlantUML diagram')]");
assertNotEquals(0, img.getImageReader().getHeight(0)); // 131
assertNotEquals(0, img.getImageReader().getWidth(0)); // 120
}
} }
} }

View File

@ -1,84 +1,76 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import java.io.ByteArrayOutputStream; import java.io.IOException;
import java.io.InputStream; import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.Locale; import java.util.Locale;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
public class TestImage extends WebappTestCase { public class TestImage extends WebappTestCase {
/** /**
* Verifies the generation of the version image from an encoded URL * Verifies the generation of the version image from an encoded URL
*/ */
public void testVersionImage() throws Exception { public void testVersionImage() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/png/" + TestUtils.VERSION);
WebRequest request = new GetMethodWebRequest(getServerUrl() + "png/" + TestUtils.VERSION); final URLConnection conn = url.openConnection();
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not PNG", "image/png", response.getContentType()); assertEquals(
"Response content type is not PNG",
"image/png",
conn.getContentType().toLowerCase()
);
// Get the image and verify its size // Get the image and verify its size
InputStream responseStream = response.getInputStream(); byte[] inMemoryImage = getContentAsBytes(conn);
ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while ((n = responseStream.read(buf)) != -1) {
imageStream.write(buf, 0, n);
}
imageStream.close();
byte[] inMemoryImage = imageStream.toByteArray();
int diagramLen = inMemoryImage.length; int diagramLen = inMemoryImage.length;
assertTrue(diagramLen > 10000); assertTrue(diagramLen > 10000);
assertTrue(diagramLen < 20000); assertTrue(diagramLen < 20000);
responseStream.close();
} }
/** /**
* Verifies that the HTTP header of a diagram incites the browser to cache it. * Verifies that the HTTP header of a diagram incites the browser to cache it.
*/ */
public void testDiagramHttpHeader() throws Exception { public void testDiagramHttpHeader() throws IOException, ParseException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/png/" + TestUtils.SEQBOB);
// Bob -> Alice : hello final URLConnection conn = url.openConnection();
WebRequest request = new GetMethodWebRequest(getServerUrl() + "png/" + TestUtils.SEQBOB);
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not PNG", "image/png", response.getContentType()); assertEquals(
"Response content type is not PNG",
"image/png",
conn.getContentType().toLowerCase()
);
// Verifies the availability of the Expires entry in the response header // Verifies the availability of the Expires entry in the response header
assertNotNull(response.getHeaderField("Expires")); assertNotNull(conn.getHeaderField("Expires"));
// Verifies the availability of the Last-Modified entry in the response header // Verifies the availability of the Last-Modified entry in the response header
assertNotNull(response.getHeaderField("Last-Modified")); assertNotNull(conn.getHeaderField("Last-Modified"));
// Verifies the Last-Modified value is in the past // Verifies the Last-Modified value is in the past
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ZZZ", Locale.ENGLISH); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ZZZ", Locale.ENGLISH);
Date lastModified = format.parse(response.getHeaderField("Last-Modified")); Date lastModified = format.parse(conn.getHeaderField("Last-Modified"));
assertTrue("Last-Modified is not in the past", lastModified.before(new Date())); assertTrue("Last-Modified is not in the past", lastModified.before(new Date()));
// Consume the response // Consume the response but do nothing with it
InputStream responseStream = response.getInputStream(); getContentAsBytes(conn);
while (responseStream.read() != -1) {
// Do nothing
}
} }
/** /**
* Verifies that the HTTP header of a diagram incites the browser to cache it. * Verifies that the HTTP header of a diagram incites the browser to cache it.
*/ */
public void testOldImgURL() throws Exception { public void testOldImgURL() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/img/" + TestUtils.SEQBOB);
// Bob -> Alice : hello final URLConnection conn = url.openConnection();
WebRequest request = new GetMethodWebRequest(getServerUrl() + "img/" + TestUtils.SEQBOB);
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not PNG", "image/png", response.getContentType()); assertEquals(
// Consume the response "Response content type is not PNG",
InputStream responseStream = response.getInputStream(); "image/png",
while (responseStream.read() != -1) { conn.getContentType().toLowerCase()
// Do nothing );
} // Consume the response but do nothing with it
getContentAsBytes(conn);
} }
} }

View File

@ -1,11 +1,8 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import java.io.IOException; import java.io.IOException;
import java.net.URL;
public class TestLanguage extends WebappTestCase { public class TestLanguage extends WebappTestCase {
@ -13,10 +10,8 @@ public class TestLanguage extends WebappTestCase {
* Tests that the language for the current PlantUML server can be obtained through HTTP * Tests that the language for the current PlantUML server can be obtained through HTTP
*/ */
public void testRetrieveLanguage() throws IOException { public void testRetrieveLanguage() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/language");
WebRequest request = new GetMethodWebRequest(getServerUrl() + "/language"); String languageText = getContentText(url);
WebResponse response = conversation.getResource(request);
String languageText = response.getText();
assertTrue("Language contains @startuml", languageText.indexOf("@startuml") > 0); assertTrue("Language contains @startuml", languageText.indexOf("@startuml") > 0);
} }

View File

@ -1,29 +1,41 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import com.meterware.httpunit.GetMethodWebRequest; import java.io.IOException;
import com.meterware.httpunit.WebConversation; import java.net.URL;
import com.meterware.httpunit.WebRequest; import java.net.URLConnection;
import com.meterware.httpunit.WebResponse;
public class TestMap extends WebappTestCase { public class TestMap extends WebappTestCase {
/** /**
* Verifies the generation of the MAP for the following sample: * Verifies the generation of the MAP for the following sample:
* *
* participant Bob [[http://www.yahoo.com]] * participant Bob [[http://www.yahoo.com]]
* Bob -> Alice : [[http://www.google.com]] hello * Bob -> Alice : [[http://www.google.com]] hello
*/ */
public void testSimpleSequenceDiagram() throws Exception { public void testSimpleSequenceDiagram() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(
WebRequest request = new GetMethodWebRequest(getServerUrl() getServerUrl() +
+ "map/AqWiAibCpYn8p2jHSCfFKeYEpYWfAR3IroylBzUhJCp8pzTBpi-DZUK2IUhQAJZcP2QdAbYXgalFpq_FIOKeLCX8pSd91m00"); "/map/AqWiAibCpYn8p2jHSCfFKeYEpYWfAR3IroylBzUhJCp8pzTBpi-DZUK2IUhQAJZcP2QdAbYXgalFpq_FIOKeLCX8pSd91m00"
WebResponse response = conversation.getResource(request); );
final URLConnection conn = url.openConnection();
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not TEXT PLAIN", "text/plain", response.getContentType()); assertEquals(
assertEquals("Response character set is not UTF-8", "UTF-8", response.getCharacterSet()); "Response content type is not TEXT PLAIN or UTF-8",
"text/plain;charset=utf-8",
conn.getContentType().toLowerCase()
);
// Get the content, check its first characters and verify its size // Get the content, check its first characters and verify its size
String diagram = response.getText(); String diagram = getContentText(conn);
assertTrue("Response content is not starting with <area", diagram.startsWith("<area")); assertTrue(
"Response content is not starting with <map",
diagram.startsWith("<map")
);
assertTrue(
"Response content (2. line) is not starting with <area",
diagram.split("\\n", 2)[1].startsWith("<area")
);
int diagramLen = diagram.length(); int diagramLen = diagram.length();
assertTrue(diagramLen > 200); assertTrue(diagramLen > 200);
assertTrue(diagramLen < 300); assertTrue(diagramLen < 300);
@ -33,33 +45,43 @@ public class TestMap extends WebappTestCase {
* Check the content of the MAP for the sequence diagram sample * Check the content of the MAP for the sequence diagram sample
* Verify structure of the area tags * Verify structure of the area tags
*/ */
public void testSequenceDiagramContent() throws Exception { public void testSequenceDiagramContent() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(
WebRequest request = new GetMethodWebRequest(getServerUrl() getServerUrl() +
+ "map/AqWiAibCpYn8p2jHSCfFKeYEpYWfAR3IroylBzUhJCp8pzTBpi-DZUK2IUhQAJZcP2QdAbYXgalFpq_FIOKeLCX8pSd91m00"); "/map/AqWiAibCpYn8p2jHSCfFKeYEpYWfAR3IroylBzUhJCp8pzTBpi-DZUK2IUhQAJZcP2QdAbYXgalFpq_FIOKeLCX8pSd91m00"
WebResponse response = conversation.getResource(request); );
// Analyze response // Analyze response
// Get the data contained in the XML // Get the data contained in the XML
String map = response.getText(); String map = getContentText(url);
assertTrue("Response is not a list of tags", map.matches("(<([^<>]+)>)+")); // Verify shape:
assertTrue("Response doesn't contain the area structure", // <map id="..." name="...">
map.matches(".*(area shape=\".+\" id=\".+\" href=\".+\").*")); // <area shape="..." id="..." href="..." ... />
// <area shape="..." id="..." href="..." ... />
// </map>
assertTrue(
"Response doesn't match shape",
map.matches("^<map id=\".+\" name=\".+\">\n(<area shape=\".+\" id=\".+\" href=\".+\".*/>\n){2}</map>\n*$")
);
} }
/** /**
* Check the empty MAP of a sequence diagram without link * Check the empty MAP of a sequence diagram without link
* This test uses the simple Bob -> Alice * This test uses the simple Bob -> Alice
*/ */
public void testSequenceDiagramWithoutLink() throws Exception { public void testSequenceDiagramWithoutLink() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/map/" + TestUtils.SEQBOB);
WebRequest request = new GetMethodWebRequest(getServerUrl() + "map/" + TestUtils.SEQBOB); final URLConnection conn = url.openConnection();
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not TEXT PLAIN", "text/plain", response.getContentType()); assertEquals(
// Get the content, check it's an empty response "Response content type is not TEXT PLAIN or UTF-8",
String diagram = response.getText(); "text/plain;charset=utf-8",
conn.getContentType().toLowerCase()
);
// Get the data contained in the XML
String diagram = getContentText(conn);
int diagramLen = diagram.length(); int diagramLen = diagram.length();
assertEquals(0, diagramLen); assertEquals(0, diagramLen);
} }
} }

View File

@ -1,52 +1,45 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import java.io.ByteArrayOutputStream; import java.io.IOException;
import java.io.InputStream; import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
public class TestOldProxy extends WebappTestCase { public class TestOldProxy extends WebappTestCase {
/** /**
* Verifies the proxified reception of the default Bob and Alice diagram * Verifies the proxified reception of the default Bob and Alice diagram
*/ */
public void testDefaultProxy() throws Exception { public void testDefaultProxy() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/proxy/" + getServerUrl() + "/resource/test2diagrams.txt");
WebRequest request = new GetMethodWebRequest(getServerUrl() + "proxy/" + getServerUrl() final URLConnection conn = url.openConnection();
+ "resource/test2diagrams.txt");
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
// assertEquals( "Response content type is not PNG", "image/png", response.getContentType()); assertEquals(
"Response content type is not PNG",
"image/png",
conn.getContentType().toLowerCase()
);
// Get the image and verify its size (~2000 bytes) // Get the image and verify its size (~2000 bytes)
InputStream responseStream = response.getInputStream(); byte[] inMemoryImage = getContentAsBytes(conn);
ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while ((n = responseStream.read(buf)) != -1) {
imageStream.write(buf, 0, n);
}
imageStream.close();
responseStream.close();
byte[] inMemoryImage = imageStream.toByteArray();
int diagramLen = inMemoryImage.length; int diagramLen = inMemoryImage.length;
assertTrue(diagramLen > 1500); assertTrue(diagramLen > 2000);
assertTrue(diagramLen < 2500); assertTrue(diagramLen < 3000);
} }
public void testProxyWithFormat() throws Exception { public void testProxyWithFormat() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/proxy/svg/" + getServerUrl() + "/resource/test2diagrams.txt");
WebRequest request = new GetMethodWebRequest(getServerUrl() + "proxy/svg/" + getServerUrl() final URLConnection conn = url.openConnection();
+ "resource/test2diagrams.txt");
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
// TODO assertEquals( "Response content type is not SVG", "image/svg+xml", response.getContentType()); assertEquals(
"Response content type is not SVG",
"image/svg+xml",
conn.getContentType().toLowerCase()
);
// Get the content and verify its size // Get the content and verify its size
String diagram = response.getText(); String diagram = getContentText(conn);
int diagramLen = diagram.length(); int diagramLen = diagram.length();
assertTrue(diagramLen > 1000); assertTrue(diagramLen > 1000);
assertTrue(diagramLen < 3000); assertTrue(diagramLen < 3000);
@ -55,15 +48,22 @@ public class TestOldProxy extends WebappTestCase {
/** /**
* Verifies that the HTTP header of a diagram incites the browser to cache it. * Verifies that the HTTP header of a diagram incites the browser to cache it.
*/ */
public void testInvalidUrl() throws Exception { public void testInvalidUrl() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/proxy/invalidURL");
// Try to proxify an invalid address final HttpURLConnection conn = (HttpURLConnection)url.openConnection();
WebRequest request = new GetMethodWebRequest(getServerUrl() + "proxy/invalidURL"); // Analyze response
WebResponse response = conversation.getResource(request); // Get the content and verify its size
// Analyze response, it must be the empty form assertEquals(
// Verifies the Content-Type header "Response is not empty",
assertEquals("Response content type is not HTML", "text/html", response.getContentType()); 0,
WebForm[] forms = response.getForms(); conn.getContentLength()
assertEquals(2, forms.length); );
// Check if status code is 400
assertEquals(
"Bad HTTP status received",
400,
conn.getResponseCode()
);
} }
} }

View File

@ -1,65 +1,105 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import java.io.ByteArrayOutputStream; import java.io.IOException;
import java.io.InputStream; import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
public class TestProxy extends WebappTestCase { public class TestProxy extends WebappTestCase {
/** /**
* Verifies the proxified reception of the default Bob and Alice diagram * Verifies the proxified reception of the default Bob and Alice diagram
*/ */
public void testDefaultProxy() throws Exception { public void testDefaultProxy() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/proxy?src=" + getServerUrl() + "/resource/test2diagrams.txt");
WebRequest request = new GetMethodWebRequest(getServerUrl() final URLConnection conn = url.openConnection();
+ "proxy?src=" + getServerUrl() + "resource/test2diagrams.txt");
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not PNG", "image/png", response.getContentType()); assertEquals(
"Response content type is not PNG",
"image/png",
conn.getContentType().toLowerCase()
);
// Get the image and verify its size (~2000 bytes) // Get the image and verify its size (~2000 bytes)
InputStream responseStream = response.getInputStream(); byte[] inMemoryImage = getContentAsBytes(conn);
ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while ((n = responseStream.read(buf)) != -1) {
imageStream.write(buf, 0, n);
}
imageStream.close();
responseStream.close();
byte[] inMemoryImage = imageStream.toByteArray();
int diagramLen = inMemoryImage.length; int diagramLen = inMemoryImage.length;
assertTrue(diagramLen > 1500); assertTrue(diagramLen > 2000);
assertTrue(diagramLen < 2500); assertTrue(diagramLen < 3000);
} }
/*
public void testProxyWithFormat() throws Exception { /**
WebConversation conversation = new WebConversation(); * Verifies the proxified reception of the default Bob and Alice diagram with defined format.
WebRequest request = new GetMethodWebRequest(getServerUrl() */
+ "proxy?format=svg&src=" + getServerUrl() + "resource/test2diagrams.txt"); public void testProxyWithFormat() throws IOException {
WebResponse response = conversation.getResource(request); final URL url = new URL(getServerUrl() + "/proxy?fmt=svg&src=" + getServerUrl() + "/resource/test2diagrams.txt");
final URLConnection conn = url.openConnection();
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals( "Response content type is not SVG", "image/svg+xml", response.getContentType()); assertEquals(
"Response content type is not SVG",
"image/svg+xml",
conn.getContentType().toLowerCase()
);
// Get the content and verify its size // Get the content and verify its size
String diagram = response.getText(); String diagram = getContentText(conn);
int diagramLen = diagram.length(); int diagramLen = diagram.length();
assertTrue(diagramLen > 1000); assertTrue(diagramLen > 2000);
assertTrue(diagramLen < 3000); assertTrue(diagramLen < 3000);
} }
/**
* Verifies the proxified reception of the default Bob and Alice diagram with defined format and format (idx=0).
*/
public void testProxyWithFormatIdx0() throws IOException {
final URL url = new URL(getServerUrl() + "/proxy?fmt=svg&idx=0&src=" + getServerUrl() + "/resource/test2diagrams.txt");
final URLConnection conn = url.openConnection();
// Analyze response
// Verifies the Content-Type header
assertEquals(
"Response content type is not SVG",
"image/svg+xml",
conn.getContentType().toLowerCase()
);
// Get the content and verify its size
String diagram = getContentText(conn);
int diagramLen = diagram.length();
assertTrue(diagramLen > 2000);
assertTrue(diagramLen < 3000);
}
/**
* Verifies the proxified reception of the default Bob and Alice diagram with defined format and format (idx=1).
*/
public void testProxyWithFormatIdx1() throws IOException {
final URL url = new URL(getServerUrl() + "/proxy?fmt=svg&idx=1&src=" + getServerUrl() + "/resource/test2diagrams.txt");
final URLConnection conn = url.openConnection();
// Analyze response
// Verifies the Content-Type header
assertEquals(
"Response content type is not SVG",
"image/svg+xml",
conn.getContentType().toLowerCase()
);
// Get the content and verify its size
String diagram = getContentText(conn);
int diagramLen = diagram.length();
assertTrue(diagramLen > 5000);
assertTrue(diagramLen < 6000);
}
/** /**
* Verifies that the HTTP header of a diagram incites the browser to cache it. * Verifies that the HTTP header of a diagram incites the browser to cache it.
*/ */
public void testInvalidUrl() throws Exception { public void testInvalidUrl() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/proxy?src=invalidURL");
// Try to proxify an invalid address final HttpURLConnection conn = (HttpURLConnection)url.openConnection();
WebRequest request = new GetMethodWebRequest(getServerUrl() + "proxy?src=invalidURL"); // Analyze response, it must be HTTP error 400
WebResponse response = conversation.getResource(request); assertEquals(
// Analyze response, it must be HTTP error 500 "Bad HTTP status received",
//assertEquals("Bad HTTP status received", 500, response.getResponseCode()); 400,
conn.getResponseCode()
);
} }
} }

View File

@ -1,28 +1,31 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import com.meterware.httpunit.GetMethodWebRequest; import java.io.IOException;
import com.meterware.httpunit.PostMethodWebRequest; import java.io.InputStream;
import com.meterware.httpunit.WebConversation; import java.io.OutputStreamWriter;
import com.meterware.httpunit.WebRequest; import java.net.HttpURLConnection;
import com.meterware.httpunit.WebResponse; import java.net.URL;
import java.net.URLConnection;
import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.Scanner; import java.util.Scanner;
public class TestSVG extends WebappTestCase { public class TestSVG extends WebappTestCase {
/** /**
* Verifies the generation of the SVG for the Bob -> Alice sample * Verifies the generation of the SVG for the Bob -> Alice sample
*/ */
public void testSimpleSequenceDiagram() throws Exception { public void testSimpleSequenceDiagram() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/svg/" + TestUtils.SEQBOB);
WebRequest request = new GetMethodWebRequest(getServerUrl() + "svg/" + TestUtils.SEQBOB); final URLConnection conn = url.openConnection();
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not SVG", "image/svg+xml", response.getContentType()); assertEquals(
"Response content type is not SVG",
"image/svg+xml",
conn.getContentType().toLowerCase()
);
// Get the content and verify its size // Get the content and verify its size
String diagram = response.getText(); String diagram = getContentText(conn);
int diagramLen = diagram.length(); int diagramLen = diagram.length();
assertTrue(diagramLen > 1000); assertTrue(diagramLen > 1000);
assertTrue(diagramLen < 3000); assertTrue(diagramLen < 3000);
@ -31,24 +34,31 @@ public class TestSVG extends WebappTestCase {
/** /**
* Verifies the generation of the SVG for the Bob -> Alice sample * Verifies the generation of the SVG for the Bob -> Alice sample
*/ */
public void testPostedSequenceDiagram() throws Exception { public void testPostedSequenceDiagram() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/svg");
PostMethodWebRequest request = new PostMethodWebRequest( final HttpURLConnection conn = (HttpURLConnection)url.openConnection();
getServerUrl() + "svg/", conn.setRequestMethod("POST");
new ByteArrayInputStream("@startuml\nBob -> Alice\n@enduml".getBytes(Charset.defaultCharset())), conn.setDoOutput(true);
"text/plain"); conn.setRequestProperty("Content-type", "text/plain");
try (final OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream())) {
WebResponse response = conversation.getResource(request); writer.write("@startuml\nBob -> Alice\n@enduml");
writer.flush();
assertEquals(200, response.getResponseCode()); }
// Analyze response // Analyze response
// HTTP response 200
assertEquals(
"Bad HTTP status received",
200,
conn.getResponseCode()
);
// Verifies the Content-Type header // Verifies the Content-Type header
assertEquals("Response content type is not SVG", "image/svg+xml", response.getContentType()); assertEquals(
"Response content type is not SVG",
"image/svg+xml",
conn.getContentType().toLowerCase()
);
// Get the content and verify its size // Get the content and verify its size
String diagram = getContentText(conn.getInputStream());
String diagram = response.getText();
int diagramLen = diagram.length(); int diagramLen = diagram.length();
assertTrue(diagramLen > 1000); assertTrue(diagramLen > 1000);
assertTrue(diagramLen < 3000); assertTrue(diagramLen < 3000);
@ -57,40 +67,51 @@ public class TestSVG extends WebappTestCase {
/** /**
* Verifies the generation of the SVG for the Bob -> Alice sample * Verifies the generation of the SVG for the Bob -> Alice sample
*/ */
public void testPostedInvalidSequenceDiagram() throws Exception { public void testPostedInvalidSequenceDiagram() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/svg");
PostMethodWebRequest request = new PostMethodWebRequest( final HttpURLConnection conn = (HttpURLConnection)url.openConnection();
getServerUrl() + "svg/", conn.setRequestMethod("POST");
new ByteArrayInputStream("@startuml\n[Bob\n@enduml".getBytes(Charset.defaultCharset())), conn.setDoOutput(true);
"text/plain"); conn.setRequestProperty("Content-type", "text/plain");
try (final OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream())) {
WebResponse response = conversation.getResource(request); writer.write("@startuml\n[Bob\n@enduml");
writer.flush();
assertEquals(400, response.getResponseCode()); }
// Analyze response
// HTTP response 400
assertEquals(
"Bad HTTP status received",
400,
conn.getResponseCode()
);
} }
/** /**
* Check the content of the SVG * Check the content of the SVG
*/ */
public void testSequenceDiagramContent() throws Exception { public void testSequenceDiagramContent() throws IOException {
WebConversation conversation = new WebConversation(); final URL url = new URL(getServerUrl() + "/svg/" + TestUtils.SEQBOB);
WebRequest request = new GetMethodWebRequest(getServerUrl() + "svg/" + TestUtils.SEQBOB);
WebResponse response = conversation.getResource(request);
// Analyze response // Analyze response
// Get the data contained in the XML // Get the data contained in the XML
Scanner s = new Scanner(response.getInputStream()).useDelimiter("(<([^<>]+)>)+"); try (
String token; final InputStream responseStream = url.openStream();
int bobCounter = 0, aliceCounter = 0; final Scanner scanner = new Scanner(responseStream).useDelimiter("(<([^<>]+)>)+")
while (s.hasNext()) { ) {
token = s.next(); String token;
if (token.startsWith("Bob")) { int bobCounter = 0;
bobCounter++; int aliceCounter = 0;
} while (scanner.hasNext()) {
if (token.startsWith("Alice")) { token = scanner.next();
aliceCounter++; if (token.startsWith("Bob")) {
bobCounter++;
}
if (token.startsWith("Alice")) {
aliceCounter++;
}
} }
assertTrue(bobCounter == 2);
assertTrue(aliceCounter == 2);
} }
assertTrue(bobCounter == 2);
assertTrue(aliceCounter == 2);
} }
} }

View File

@ -4,7 +4,7 @@ package net.sourceforge.plantuml.servlet;
/** /**
* Utility class for the unit tests * Utility class for the unit tests
*/ */
public class TestUtils { public abstract class TestUtils {
/* /*
* Theses strings are the compressed form of a PlantUML diagram. * Theses strings are the compressed form of a PlantUML diagram.
@ -20,8 +20,4 @@ public class TestUtils {
*/ */
public static final String SEQBOB = "SyfFKj2rKt3CoKnELR1Io4ZDoSa70000"; public static final String SEQBOB = "SyfFKj2rKt3CoKnELR1Io4ZDoSa70000";
protected TestUtils() {
// prevents calls from subclass
throw new UnsupportedOperationException();
}
} }

View File

@ -1,22 +1,47 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import junit.framework.TestCase; import junit.framework.TestCase;
import net.sourceforge.plantuml.servlet.server.EmbeddedJettyServer;
import net.sourceforge.plantuml.servlet.server.ExternalServer;
import net.sourceforge.plantuml.servlet.server.ServerUtils;
public abstract class WebappTestCase extends TestCase { public abstract class WebappTestCase extends TestCase {
private ServerUtils serverUtils; private final ServerUtils serverUtils;
public WebappTestCase() { public WebappTestCase() {
super(); this(null);
} }
public WebappTestCase(String name) { public WebappTestCase(String name) {
super(name); super(name);
String uri = System.getProperty("system.test.server", "");
//uri = "http://localhost:8080/plantuml";
if (!uri.isEmpty()) {
// mvn test -DskipTests=false -DargLine="-Dsystem.test.server=http://localhost:8080/plantuml"
System.out.println("Test against external server: " + uri);
serverUtils = new ExternalServer(uri);
return;
}
// mvn test -DskipTests=false
System.out.println("Test against embedded jetty server.");
serverUtils = new EmbeddedJettyServer();
} }
@Override @Override
public void setUp() throws Exception { public void setUp() throws Exception {
serverUtils = new ServerUtils(true); serverUtils.startServer();
} }
@Override @Override
@ -28,4 +53,54 @@ public abstract class WebappTestCase extends TestCase {
return serverUtils.getServerUrl(); return serverUtils.getServerUrl();
} }
public String getContentText(final URL url) throws IOException {
try (final InputStream responseStream = url.openStream()) {
return getContentText(responseStream);
}
}
public String getContentText(final URLConnection conn) throws IOException {
try (final InputStream responseStream = conn.getInputStream()) {
return getContentText(responseStream);
}
}
public String getContentText(final InputStream stream) throws IOException {
try (
final InputStreamReader isr = new InputStreamReader(stream);
final BufferedReader br = new BufferedReader(isr);
) {
String line;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
return sb.toString().trim();
}
}
public byte[] getContentAsBytes(final URL url) throws IOException {
try (final InputStream responseStream = url.openStream()) {
return getContentAsBytes(responseStream);
}
}
public byte[] getContentAsBytes(final URLConnection conn) throws IOException {
try (final InputStream responseStream = conn.getInputStream()) {
return getContentAsBytes(responseStream);
}
}
public byte[] getContentAsBytes(final InputStream stream) throws IOException {
try (final ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
byte[] buf = new byte[1024];
int n = 0;
while ((n = stream.read(buf)) != -1) {
byteStream.write(buf, 0, n);
}
return byteStream.toByteArray();
}
}
} }

View File

@ -1,4 +1,4 @@
package net.sourceforge.plantuml.servlet; package net.sourceforge.plantuml.servlet.server;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
@ -6,20 +6,14 @@ import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.webapp.WebAppContext;
public class ServerUtils {
public class EmbeddedJettyServer implements ServerUtils {
private Server server; private Server server;
public ServerUtils(boolean start) throws Exception { public EmbeddedJettyServer() {
server = new Server(new InetSocketAddress("127.0.0.1", 0)); server = new Server(new InetSocketAddress("127.0.0.1", 0));
server.addBean(new WebAppContext(server, "src/main/webapp", "/plantuml")); server.addBean(new WebAppContext(server, "src/main/webapp", "/plantuml"));
if (start) {
startServer();
}
}
public ServerUtils() throws Exception {
this(false);
} }
public void startServer() throws Exception { public void startServer() throws Exception {
@ -32,7 +26,7 @@ public class ServerUtils {
public String getServerUrl() { public String getServerUrl() {
Connector connector = server.getConnectors()[0]; Connector connector = server.getConnectors()[0];
return String.format("http://%s:%d/plantuml/", connector.getHost(), connector.getLocalPort()); return String.format("http://%s:%d/plantuml", connector.getHost(), connector.getLocalPort());
} }
} }

View File

@ -0,0 +1,23 @@
package net.sourceforge.plantuml.servlet.server;
public class ExternalServer implements ServerUtils {
private final String uri;
public ExternalServer(String uri) {
this.uri = uri;
}
@Override
public void startServer() throws Exception { }
@Override
public void stopServer() throws Exception { }
@Override
public String getServerUrl() {
return this.uri;
}
}

View File

@ -0,0 +1,12 @@
package net.sourceforge.plantuml.servlet.server;
public interface ServerUtils {
public void startServer() throws Exception;
public void stopServer() throws Exception;
public abstract String getServerUrl();
}