/*
* $Id: HTTPTestCase.java 6825 2006-04-04 03:00:44Z dfs $
*
* Copyright 2006 Daniel F. Savarese
*
* 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.savarese.org/software/ApacheLicense-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.savarese.barehttp;
import java.io.*;
import java.util.*;
import junit.framework.*;
/**
* An abstract class that provides support for testing HTTP requests
* by creating a temporary file, filling it with random data, issuing
* requests for the file, and comparing the retrieved data with the
* original data. Subclasses must override the package-scoped
* issueRequest method.
*
* @author <a href="http://www.savarese.org/">Daniel F. Savarese</a>
*/
public abstract class HTTPTestCase extends TestCase {
static final int MAX_FILE_SIZE = 1024;
static final String EOL = "\r\n";
File file;
String docroot;
byte[] data;
Random random;
public HTTPTestCase() throws IOException {
random = new Random();
// There's no point in doing this for tests that don't need it, so
// we don't put it in setUp
file = File.createTempFile("barehttp", null);
docroot = file.getCanonicalFile().getParent();
data = new byte[random.nextInt(MAX_FILE_SIZE) + 1];
random.nextBytes(data);
FileOutputStream output = new FileOutputStream(file);
output.write(data);
output.close();
file.deleteOnExit();
}
abstract byte[] issueRequest(String request) throws IOException;
void validateOutput(byte[] output, boolean skipHeaders) {
int skip = 0;
if(skipHeaders) {
while(skip < output.length) {
if(output[skip++] == '\r' && skip < output.length &&
output[skip++] == '\n' && skip < output.length &&
output[skip++] == '\r' && skip < output.length &&
output[skip++] == '\n')
break;
}
}
assertEquals("Expected data length differs from output data length.",
data.length, output.length - skip);
int i;
for(i=0; skip < output.length && output[skip] == data[i]; ++skip, ++i);
assertEquals("Expected data and output data differ at data offset " +
i + " and output offset " + skip, output.length, skip);
}
/**
* Tests an HTTP 0.9 simple request.
*/
public void testGetRequest09() throws IOException {
String get = "GET /" + file.getName() + EOL;
validateOutput(issueRequest(get), false);
}
/**
* Tests an HTTP 1.1 GET request.
*/
public void testGetRequest11() throws IOException {
String get =
"GET /" + file.getName() + " HTTP/1.1" + EOL +
"Host: localhost" + EOL + EOL;
validateOutput(issueRequest(get), true);
}
}
|