Skip to content

Commit

Permalink
ExpediaGroup#101 Tests should pass in windows. New fixes and performa…
Browse files Browse the repository at this point in the history
…nce improvements.
  • Loading branch information
a-dlatorre committed Mar 12, 2018
1 parent cdfedae commit fe49cd1
Show file tree
Hide file tree
Showing 14 changed files with 90 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package com.hotels.styx.api.messages;

import java.lang.reflect.Field;
import java.util.Objects;
import java.util.stream.Stream;

import static java.lang.reflect.Modifier.isStatic;
Expand Down Expand Up @@ -134,4 +135,18 @@ public String description() {
public String toString() {
return code + " " + description;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HttpResponseStatus that = (HttpResponseStatus) o;
return code == that.code;
}

@Override
public int hashCode() {

return Objects.hash(code);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ private List<String> pathToComponents(Path path) {

private String removeAsterisk(String path) {
String newPath = path;
if (path.endsWith("*")) {
if (path.endsWith("/*")) {
newPath = path.substring(0, path.length() - 1);
}
return newPath;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,16 @@ private ResourceContentMatcher(String expected) {
this.expected = checkNotNull(expected);
}

/**
* Returns a Matcher that will compare the textual content of this {@link Resource} (using UTF-8 encoding)
* to the provided String. Line separator differences will be ignored as long the CRLF or LF sequences
* are used for line breaks.
*
* @param expected text string to which this resource will be compared.
* @return
*/
public static ResourceContentMatcher contains(String expected) {
return new ResourceContentMatcher(expected);
return new ResourceContentMatcher(expected.replace("\r\n", "\n"));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright (C) 2013-2017 Expedia Inc.
* Copyright (C) 2013-2018 Expedia Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -34,6 +34,7 @@

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.net.MediaType.JSON_UTF_8;
import static com.hotels.styx.admin.support.Json.PRETTY_PRINTER;
import static com.hotels.styx.api.HttpResponse.Builder.response;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_IMPLEMENTED;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright (C) 2013-2017 Expedia Inc.
* Copyright (C) 2013-2018 Expedia Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,6 +16,8 @@
package com.hotels.styx.admin.handlers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.eventbus.EventBus;
Expand All @@ -34,6 +36,7 @@

import static com.fasterxml.jackson.databind.SerializationFeature.FAIL_ON_EMPTY_BEANS;
import static com.google.common.net.MediaType.JSON_UTF_8;
import static com.hotels.styx.admin.support.Json.PRETTY_PRINTER;
import static com.hotels.styx.api.HttpResponse.Builder.response;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.slf4j.LoggerFactory.getLogger;
Expand All @@ -44,7 +47,8 @@
public class OriginsInventoryHandler extends BaseHttpHandler implements OriginsInventoryStateChangeListener {
private static final Logger LOG = getLogger(OriginsInventoryHandler.class);

private final ObjectMapper mapper = new ObjectMapper().disable(FAIL_ON_EMPTY_BEANS);
private final ObjectMapper mapper = new ObjectMapper().disable(FAIL_ON_EMPTY_BEANS)
.setDefaultPrettyPrinter(PRETTY_PRINTER);

private final Map<Id, OriginsInventorySnapshot> originsInventorySnapshotMap = new ConcurrentHashMap<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,34 +15,22 @@
*/
package com.hotels.styx.admin.handlers;

import com.google.common.io.CharStreams;
import com.hotels.styx.api.Resource;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

import static com.google.common.base.Throwables.propagate;
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;
import java.io.InputStreamReader;
import java.io.Reader;

final class Resources {
private Resources() {
}

public static String load(Resource resource) throws IOException {
try {
return fileContents(Paths.get(resource.url().toURI()));
} catch (URISyntaxException e) {
throw propagate(e);
try (Reader reader = new BufferedReader(new InputStreamReader(resource.inputStream()))) {
return CharStreams.toString(reader);
}
}

private static String fileContents(Path path) throws IOException {
try (Stream<String> lines = Files.lines(path)) {
return lines.collect(joining(lineSeparator()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@
public final class Json {
// Always uses unix-style line separators regardless of platform
public static final PrettyPrinter PRETTY_PRINTER = new DefaultPrettyPrinter()
.withObjectIndenter(new DefaultIndenter().withLinefeed("\n"))
.withArrayIndenter(new DefaultIndenter().withLinefeed("\n"));

.withObjectIndenter(new DefaultIndenter().withLinefeed("\n"));

private Json() {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.MapType;
import com.google.common.base.Charsets;
import com.google.common.eventbus.EventBus;
import com.hotels.styx.admin.tasks.StubConnectionPool;
import com.hotels.styx.api.Id;
Expand Down Expand Up @@ -87,20 +88,21 @@ public void prettyPrintsOriginsSnapshot() {
eventBus.post(new OriginsInventorySnapshot(APP_ID, pool(emptySet()), pool(emptySet()), pool(disabledOrigins)));

FullHttpResponse response = waitForResponse(handler.handle(get("/?pretty=1").build()));
assertThat(response.bodyAs(UTF_8), matchesRegex("\\{\n" +
" \"" + APP_ID + "\" : \\{\n" +
" \"appId\" : \"" + APP_ID + "\",\n" +
" \"activeOrigins\" : \\[ ],\n" +
" \"inactiveOrigins\" : \\[ ],\n" +
" \"disabledOrigins\" : \\[ \\{\n" +
" \"id\" : \"origin.\",\n" +
" \"host\" : \"localhost:....\"\n" +
" }, \\{\n" +
" \"id\" : \"origin.\",\n" +
" \"host\" : \"localhost:....\"\n" +
" } ]\n" +
" }\n" +
"}"));
assertThat(body(response).replace("\r\n", "\n"),
matchesRegex("\\{\n" +
" \"" + APP_ID + "\" : \\{\n" +
" \"appId\" : \"" + APP_ID + "\",\n" +
" \"activeOrigins\" : \\[ ],\n" +
" \"inactiveOrigins\" : \\[ ],\n" +
" \"disabledOrigins\" : \\[ \\{\n" +
" \"id\" : \"origin.\",\n" +
" \"host\" : \"localhost:....\"\n" +
" }, \\{\n" +
" \"id\" : \"origin.\",\n" +
" \"host\" : \"localhost:....\"\n" +
" } ]\n" +
" }\n" +
"}"));
}

@Test
Expand Down Expand Up @@ -133,4 +135,8 @@ private static List<RemoteHost> pool(Set<Origin> origins) {
.map(pool -> remoteHost(pool.getOrigin(), pool, mock(StyxHostHttpClient.class)))
.collect(toList());
}

private String body(FullHttpResponse response){
return response.bodyAs(Charsets.UTF_8).replace("\r\n", "\n");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ public void readsClassPathResources() {
FullHttpResponse response = waitForResponse(handler.handle(request));

assertThat(response.status(), is(OK));
assertThat(response.contentLength(), isValue("Foo\nBar\n".length()));
assertThat(body(response), is("Foo\nBar\n"));
}

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@
<maven-resources-plugin.version>2.6</maven-resources-plugin.version>
<maven-site-plugin.version>3.3</maven-site-plugin.version>
<maven-source-plugin.version>2.2.1</maven-source-plugin.version>
<maven-surefire-plugin.version>2.16</maven-surefire-plugin.version>
<maven-surefire-plugin.version>2.19</maven-surefire-plugin.version>

<!-- non apache plugin versions and configurations, please sort alphabetically -->
<animal-sniffer-maven-plugin.version>1.0</animal-sniffer-maven-plugin.version>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright (C) 2013-2017 Expedia Inc.
* Copyright (C) 2013-2018 Expedia Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -106,7 +106,7 @@ public void describeTo(Description description) {
@Override
protected boolean matchesSafely(ILoggingEvent event) {
return this.level.equals(event.getLevel())
&& this.message.matches(event.getFormattedMessage().replace("\n", ""))
&& this.message.matches(event.getFormattedMessage().replace(System.lineSeparator(), ""))
&& exceptionMatches(event.getThrowableProxy());
}

Expand Down Expand Up @@ -138,7 +138,7 @@ public void describeTo(Description description) {
@Override
protected boolean matchesSafely(IThrowableProxy item) {
return exceptionClass.equals(item.getClassName())
&& exceptionMessage.matches(item.getMessage().replace("\n", ""))
&& exceptionMessage.matches(item.getMessage().replace(System.lineSeparator(), ""))
&& item.getStackTraceElementProxyArray().length > 0;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
/**
* Copyright (C) 2013-2018 Expedia Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright (C) 2013-2018 Expedia Inc.
*
Expand All @@ -15,11 +30,11 @@
*/
package com.hotels.styx.admin

import java.io.ByteArrayInputStream
import java.io.{ByteArrayInputStream, File}
import java.nio.charset.StandardCharsets.UTF_8
import java.nio.file.Files.{copy, delete}
import java.nio.file.Path
import java.nio.file.StandardCopyOption.REPLACE_EXISTING
import java.nio.file.{Files, Path, Paths}

import com.google.common.io.Files.createTempDir
import com.hotels.styx.api.messages.FullHttpRequest.get
Expand All @@ -39,7 +54,7 @@ class FileBasedOriginsFileChangeMonitorSpec extends FunSpec
with Eventually {

val tempDir = createTempDir()
val styxOriginsFile = Paths.get(tempDir.toString, "origins.yml")
val styxOriginsFile = new File(tempDir, "origins.yml").toPath

val origin = FakeHttpServer.HttpStartupConfig(appId = "app", originId="app").start()

Expand Down Expand Up @@ -78,7 +93,7 @@ class FileBasedOriginsFileChangeMonitorSpec extends FunSpec
| backendServiceRegistry:
| class: "com.hotels.styx.proxy.backends.file.FileBackedBackendServicesRegistry$$Factory"
| config:
| originsFile: "${styxOriginsFile.toString}"
| originsFile: "${styxOriginsFile.toString.replace("\\","/")}"
| monitor:
| enabled: true
""".stripMargin
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class PluginToggleSpec extends FunSpec with StyxProxySpec with StyxClientSupplie
resp2.status() should be (OK)
resp2.bodyAs(UTF_8) should include("response-from-plugin")

checkPluginEnabled() should be("enabled\n")
checkPluginEnabled().trim should be("enabled")
}

override protected def afterAll(): Unit = {
Expand Down Expand Up @@ -79,17 +79,17 @@ class PluginToggleSpec extends FunSpec with StyxProxySpec with StyxClientSupplie
disablePlugin()

val outcome = setPluginEnabled("true")
outcome should be("{\"message\":\"State of 'pluginUnderTest' changed to 'enabled'\",\"plugin\":{\"name\":\"pluginUnderTest\",\"state\":\"enabled\"}}"+System.lineSeparator)
checkPluginEnabled() should be("enabled\n")
outcome.trim should be("{\"message\":\"State of 'pluginUnderTest' changed to 'enabled'\",\"plugin\":{\"name\":\"pluginUnderTest\",\"state\":\"enabled\"}}")
checkPluginEnabled().trim should be("enabled")
}
}

private def disablePlugin() = {
val outcome = setPluginEnabled("false")

outcome should be("{\"message\":\"State of 'pluginUnderTest' changed to 'disabled'\",\"plugin\":{\"name\":\"pluginUnderTest\",\"state\":\"disabled\"}}"+System.lineSeparator)
outcome.trim should be("{\"message\":\"State of 'pluginUnderTest' changed to 'disabled'\",\"plugin\":{\"name\":\"pluginUnderTest\",\"state\":\"disabled\"}}")

checkPluginEnabled() should be("disabled\n")
checkPluginEnabled().trim should be("disabled")
}

private def setPluginEnabled(enabled : String): String = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,10 @@ import io.netty.handler.codec.http.HttpVersion.HTTP_1_1
import io.netty.handler.codec.http._
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.{hasItem, is}
import org.scalatest.FunSpec
import org.scalatest.concurrent.Eventually
import org.scalatest.{FunSpec, Ignore}

import scala.concurrent.duration._
@Ignore
class BadRequestsSpec extends FunSpec
with StyxProxySpec
with TestClientSupport
Expand Down Expand Up @@ -133,7 +132,7 @@ class BadRequestsSpec extends FunSpec
assert(response.status == BAD_REQUEST, s"\nExpecting 400 Bad Request in message: \n$response \n\n$content\n\n")
assertThat(response.headers().get(STYX_INFO_DEFAULT), matchesRegex("noJvmRouteSet;"))

assertThat(loggingSupport.log(), hasItem(loggingEvent(ERROR, "Failure status=\"400 Bad Request\"", "io.netty.handler.codec.DecoderException", "com.hotels.styx.server.BadRequestException: Bad Host header.*")))
assertThat(loggingSupport.log(), hasItem(loggingEvent(ERROR, "Failure status=\"400 Bad Request\"", "io.netty.handler.codec.DecoderException", "com.hotels.styx.server.BadRequestException: Bad Host header. .*")))
}
}

Expand Down

0 comments on commit fe49cd1

Please sign in to comment.