⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 postwritertest.java

📁 测试工具
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
     */
    private void setupFormData(HTTPSampler httpSampler, String titleValue, String descriptionValue) {
        setupFormData(sampler, false, titleValue, descriptionValue);
    }

    /**
     * Setup the form data with specified values
     * 
     * @param httpSampler
     */
    private void setupFormData(HTTPSampler httpSampler, boolean isEncoded, String titleValue, String descriptionValue) {
        Arguments args = new Arguments();
        HTTPArgument argument1 = new HTTPArgument("title", titleValue, isEncoded);
        HTTPArgument argument2 = new HTTPArgument("description", descriptionValue, isEncoded);
        args.addArgument(argument1);
        args.addArgument(argument2);
        httpSampler.setArguments(args);
    }

    private void establishConnection() throws MalformedURLException { 
        connection = new StubURLConnection("http://fake_url/test");
    }
    
    /**
     * Create the expected output post body for form data and file multiparts
     * with default values for field names
     */
    private byte[] createExpectedOutput(
            String boundaryString,
            String contentEncoding,
            String titleValue,
            String descriptionValue,
            byte[] fileContent) throws IOException {
        return createExpectedOutput(boundaryString, contentEncoding, "title", titleValue, "description", descriptionValue, "upload", fileContent);
    }

    /**
     * Create the expected output post body for form data and file multiparts
     * with specified values
     */
    private byte[] createExpectedOutput(
            String boundaryString,
            String contentEncoding,
            String titleField,
            String titleValue,
            String descriptionField,
            String descriptionValue,
            String fileField,
            byte[] fileContent) throws IOException {
        // Create the multiparts
        byte[] formdataMultipart = createExpectedFormdataOutput(boundaryString, contentEncoding, titleField, titleValue, descriptionField, descriptionValue, true, false);
        byte[] fileMultipart = createExpectedFilepartOutput(boundaryString, fileField, temporaryFile, "text/plain", fileContent, false, true);
        
        // Join the two multiparts
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        output.write(formdataMultipart);
        output.write(fileMultipart);
        
        output.flush();
        output.close();
        
        return output.toByteArray();
    }

    /**
     * Create the expected output multipart/form-data, with only form data,
     * and no file multipart
     * 
     * @param lastMultipart true if this is the last multipart in the request
     */
    private byte[] createExpectedFormdataOutput(
            String boundaryString,
            String contentEncoding,
            String titleField,
            String titleValue,
            String descriptionField,
            String descriptionValue,
            boolean firstMultipart,
            boolean lastMultipart) throws IOException {
        final byte[] DASH_DASH = "--".getBytes(HTTP_ENCODING);
        // All form parameter always have text/plain as mime type
        final String mimeType="text/plain";//TODO make this a parameter?
        
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        if(firstMultipart) {
            output.write(DASH_DASH);
            output.write(boundaryString.getBytes(HTTP_ENCODING));
            output.write(CRLF);
        }
        output.write("Content-Disposition: form-data; name=\"".getBytes(HTTP_ENCODING));
        output.write(titleField.getBytes(HTTP_ENCODING));
        output.write("\"".getBytes(HTTP_ENCODING));
        output.write(CRLF);
        output.write("Content-Type: ".getBytes(HTTP_ENCODING));
        output.write(mimeType.getBytes(HTTP_ENCODING));
        output.write("; charset=".getBytes(HTTP_ENCODING));
        output.write((contentEncoding==null ? PostWriter.ENCODING : contentEncoding).getBytes(HTTP_ENCODING));
        output.write(CRLF);
        output.write("Content-Transfer-Encoding: 8bit".getBytes(HTTP_ENCODING));
        output.write(CRLF);
        output.write(CRLF);
        if(contentEncoding != null) {
            output.write(titleValue.getBytes(contentEncoding));
        }
        else {
            output.write(titleValue.getBytes());
        }
        output.write(CRLF);
        output.write(DASH_DASH);
        output.write(boundaryString.getBytes(HTTP_ENCODING));
        output.write(CRLF);
        output.write("Content-Disposition: form-data; name=\"".getBytes(HTTP_ENCODING));
        output.write(descriptionField.getBytes(HTTP_ENCODING));
        output.write("\"".getBytes(HTTP_ENCODING));
        output.write(CRLF);
        output.write("Content-Type: ".getBytes(HTTP_ENCODING));
        output.write(mimeType.getBytes(HTTP_ENCODING));
        output.write("; charset=".getBytes(HTTP_ENCODING));
        output.write((contentEncoding==null ? PostWriter.ENCODING : contentEncoding).getBytes(HTTP_ENCODING));
        output.write(CRLF);
        output.write("Content-Transfer-Encoding: 8bit".getBytes(HTTP_ENCODING));
        output.write(CRLF);
        output.write(CRLF);
        if(contentEncoding != null) {
            output.write(descriptionValue.getBytes(contentEncoding));
        }
        else {
            output.write(descriptionValue.getBytes());
        }
        output.write(CRLF);
        output.write(DASH_DASH);
        output.write(boundaryString.getBytes(HTTP_ENCODING));
        if(lastMultipart) {
            output.write(DASH_DASH);
        }
        output.write(CRLF);
                
        output.flush();
        output.close();

        return output.toByteArray();
    }
    
    /**
     * Create the expected file multipart
     * 
     * @param lastMultipart true if this is the last multipart in the request
     */
    private byte[] createExpectedFilepartOutput(
            String boundaryString,
            String fileField,
            File file,
            String mimeType,
            byte[] fileContent,
            boolean firstMultipart,
            boolean lastMultipart) throws IOException {
        // The encoding used for http headers and control information
        final String httpEncoding = "ISO-8859-1";
        final byte[] DASH_DASH = "--".getBytes(httpEncoding);
        
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        if(firstMultipart) {
            output.write(DASH_DASH);
            output.write(boundaryString.getBytes(httpEncoding));
            output.write(CRLF);
        }
        // replace all backslash with double backslash
        String filename = file.getName();
        output.write("Content-Disposition: form-data; name=\"".getBytes(httpEncoding));
        output.write(fileField.getBytes(httpEncoding));
        output.write(("\"; filename=\"" + filename + "\"").getBytes(httpEncoding));
        output.write(CRLF);
        output.write("Content-Type: ".getBytes(httpEncoding));
        output.write(mimeType.getBytes(httpEncoding));
        output.write(CRLF);
        output.write("Content-Transfer-Encoding: binary".getBytes(httpEncoding));
        output.write(CRLF);
        output.write(CRLF);
        output.write(fileContent);
        output.write(CRLF);
        output.write(DASH_DASH);
        output.write(boundaryString.getBytes(httpEncoding));
        if(lastMultipart) {
            output.write(DASH_DASH);
        }
        output.write(CRLF);
        
        output.flush();
        output.close();

        return output.toByteArray();
    }

    /**
     * Check that the the two byte arrays have identical content
     * 
     * @param expected
     * @param actual
     * @throws UnsupportedEncodingException 
     */
    private void checkArraysHaveSameContent(byte[] expected, byte[] actual) throws UnsupportedEncodingException {
        if(expected != null && actual != null) {
            if(expected.length != actual.length) {
            	System.out.println(new String(expected,UTF_8));
            	System.out.println("--------------------");
            	System.out.println(new String(actual,UTF_8));
            	System.out.println("====================");
                fail("arrays have different length, expected is " + expected.length + ", actual is " + actual.length);
            }
            else {
                for(int i = 0; i < expected.length; i++) {
                    if(expected[i] != actual[i]) {
                       	System.out.println(new String(expected,0,i+1));
                    	System.out.println("--------------------");
                    	System.out.println(new String(actual,0,i+1));
                    	System.out.println("====================");
                        fail("byte at position " + i + " is different, expected is " + expected[i] + ", actual is " + actual[i]);
                    }
                }
            }
        }
        else {
            fail("expected or actual byte arrays were null");
        }
    }

    /**
     * Check that the the two byte arrays different content
     * 
     * @param expected
     * @param actual
     */
    private void checkArraysHaveDifferentContent(byte[] expected, byte[] actual) {
        if(expected != null && actual != null) {
            if(expected.length == actual.length) {
                boolean allSame = true;
                for(int i = 0; i < expected.length; i++) {
                    if(expected[i] != actual[i]) {
                        allSame = false;
                        break;
                    }
                }
                if(allSame) {
                    fail("all bytes were equal");
                }
            }
        }
        else {
            fail("expected or actual byte arrays were null");
        }
    }
    
    private void checkContentTypeMultipart(HttpURLConnection conn, String boundaryString) {
        assertEquals("multipart/form-data; boundary=" + boundaryString, conn.getRequestProperty("Content-Type"));
    }

    private void checkContentTypeUrlEncoded(HttpURLConnection conn) {
        assertEquals(HTTPSamplerBase.APPLICATION_X_WWW_FORM_URLENCODED, conn.getRequestProperty("Content-Type"));
    }

    private void checkContentLength(HttpURLConnection conn, int length) {
        assertEquals(Integer.toString(length), conn.getRequestProperty("Content-Length"));
    }

    /**
     * Mock an HttpURLConnection.
     * extends HttpURLConnection instead of just URLConnection because there is a cast in PostWriter.
     */
    private static class StubURLConnection extends HttpURLConnection {
        private ByteArrayOutputStream output = new ByteArrayOutputStream();
        private Map properties = new HashMap();
        
        public StubURLConnection(String url) throws MalformedURLException {
            super(new URL(url));
        }

        public void connect() throws IOException {
        }
        
        public OutputStream getOutputStream() throws IOException {
            return output;
        }

        public void disconnect() {
        }

        public boolean usingProxy() {
            return false;
        }

        public String getRequestProperty(String key) {
            return (String) properties.get(key);
        }

        public void setRequestProperty(String key, String value) {
            properties.put(key, value);
        }
        
        public byte[] getOutputStreamContent() {
            return output.toByteArray();
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -