package com.groupon.seleniumgridextras.utilities;

import org.junit.Test;

import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.URL;
import java.net.UnknownHostException;

import static org.junit.Assert.assertEquals;

public class HttpUtilityTest {

  @Test(expected = ConnectException.class)
  public void testConnectionRefusedError() throws Exception {
    ServerSocket serverSocket = new ServerSocket(0);
    int port = serverSocket.getLocalPort();
    serverSocket
        .close(); //Find a garanteed open port by taking one and closing. Why doesn't Java allow me to get a list of open ports?
    HttpUtility.getRequest(new URL("http://localhost:" + port)).getResponseCode();
  }

  @Test
  public void test404Page() throws Exception {
    assertEquals(404, HttpUtility.getRequest(new URL("https://xkcd.com/404")).getResponseCode());
  }

  @Test
  public void test200Page() throws Exception {
    assertEquals(200, HttpUtility.getRequest(new URL("http://google.com")).getResponseCode());
  }

  @Test(expected = UnknownHostException.class)
  public void testUnknownHost() throws Exception {
    HttpUtility.getRequest(new URL("http://googasdfasfdkjashfdkjahsfdle.com/")).getResponseCode();
  }

  @Test
  public void testGetAsString() throws Exception {
    assertEquals("", HttpUtility.getRequestAsString(new URL("https://xkcd.com/404")));
  }

    @Test
    public void testCheckIfUrlStatusCode() throws Exception{
        assertEquals(200, HttpUtility.checkIfUrlStatusCode(new URL("http://google.com")));
        assertEquals(404, HttpUtility.checkIfUrlStatusCode(new URL("https://xkcd.com/404")));
        assertEquals(301, HttpUtility.checkIfUrlStatusCode(new URL("http://github.com/groupon/Selenium-Grid-Extras/releases/download/v1.5.0/SeleniumGridExtras-1.5.0-SNAPSHOT-jar-with-dependencies.jar")));
        assertEquals(200, HttpUtility.checkIfUrlStatusCode(new URL("https://github.com/groupon/Selenium-Grid-Extras/releases/download/v1.5.0/SeleniumGridExtras-1.5.0-SNAPSHOT-jar-with-dependencies.jar")));
    }

}

@@ -236,16 +236,59 @@
 tEquals;
+%0Aimport static org.junit.Assert.assertTrue;
 %0A%0Apublic
@@ -1073,48 +1073,9 @@
 Test
-(expected = UnknownHostException.class)
 %0A
+
   pu
@@ -1117,24 +1117,81 @@
 Exception %7B%0A
+    boolean expectedExceptionThrown = false;%0A    try %7B%0A  
     HttpUtil
@@ -1269,32 +1269,310 @@
 ResponseCode();%0A
+    %7D%0A    catch (UnknownHostException uhe)%0A    %7B%0A      expectedExceptionThrown = true;%0A    %7D%0A    catch (ConnectException ce)%0A    %7B%0A        expectedExceptionThrown = true;%0A    %7D%0A    assertTrue(%22Expected either UnknownHostException or ConnectException%22, expectedExceptionThrown);%0A
   %7D%0A%0A  @Test%0A  p

fix test so that the expected result doesn't depend on the DNS configuration of the network the test runs on