一个mock https server的例子

前言

在开发阶段无法跟实际第三方系统服务器端交互,或者第三方服务器端没有提供测试环境时,测试人员需要提供一个模拟的服务器端,本文提供了mock server的代码,且提供客户端连接时绕开证书校验步骤(即客户端用https连接前,无需导入证书)。

代码

文件读写(非必须,保存请求json用)

文件读写代码片.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;

public class MyFile {
	// 使用BufferedReader / BufferedWriter
	public void write(File file, StringBuffer sb) {
		try {
			if (!file.exists())
				file.createNewFile();
			BufferedWriter bw = new BufferedWriter(new FileWriter(file));
			bw.write(sb.toString());
			bw.flush();
			bw.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public StringBuffer read(File file) {
		StringBuffer content = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line;
			while ((line = br.readLine()) != null) {
				content.append(line + "\n");
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}
	//使用 InputStream / OutputStream 读写
	public StringBuffer readFile1(String path)  {
		try {
			InputStream in = new FileInputStream(path);
			byte[] data = new byte[in.available()];
			in.read(data);
			in.close();
			return new StringBuffer(new String(data));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void writeFile1(String path, StringBuffer sb) {
		try {
			OutputStream out = new FileOutputStream(path);
			out.write(sb.toString().getBytes());
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//使用 FileWriter / FileReader 读写文件
	public StringBuffer readFile2(String path) {
		File f = new File(path);
		try {
			FileReader fr = new FileReader(f);
			char[] cbuf = new char[(int) f.length()];
			fr.read(cbuf);
			fr.close();
//			return new String(cbuf);
			
			StringBuffer sb = new StringBuffer();
			for (char c:cbuf)
				sb.append(c);
			return sb;	

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void writeFile2(String path, StringBuffer sb) {
		File f = new File(path);
		try {
			FileWriter fw = new FileWriter(f);
			fw.write(sb.toString());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

HTTP客户端操作(绕过客户端证书校验)

代码片.

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.duliday.utils.MyFile;

public class SSLClient {
	private static Logger logger = LoggerFactory.getLogger(SSLClient.class);
	//绕过ssl认证
	public HttpClient wrapClient() {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
			return httpclient;
		} catch (Exception e) {
			return HttpClients.createDefault();
		}
	}

	public JSONObject post(CloseableHttpClient httpclient, String url, String body) {
		CloseableHttpResponse response = null;
		try {
			HttpPost post = new HttpPost(url);
			StringEntity postingString = new StringEntity(body, "utf-8");
			post.setEntity(postingString);
			post.setHeader("Content-Type", "application/json");
			response = httpclient.execute(post);
			String result = EntityUtils.toString(response.getEntity());
			JSONObject js = JSONObject.parseObject(result);
			return js;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static void main(String[] args) {
		SSLClient https = new SSLClient();
		CloseableHttpClient httpclient = null;
		MyFile fil = new MyFile();
		httpclient = (CloseableHttpClient) https.wrapClient();
		String url = "https://localhost:16790";
		//请求的json内容在文件中
		String body = fil.readFile1("C:\\work\\myproj\\demo\\request.txt").toString();
		JSONObject js = https.post(httpclient, url, body);
		logger.info("get Response: " + js.get("response").toString());
	}
}

模拟HTTPS 服务器端

import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import com.sun.net.httpserver.spi.HttpServerProvider;
import com.test.duliday.util.MyConst;
import com.test.duliday.util.MyLogger;
public class MyHttpsServer {
	private static SSLContext getSslContext() throws Exception {
	    KeyStore ks = KeyStore.getInstance("JKS");
	    String KEYSTORE_FILE = "C:\\src\\myserv_ks";
	    String KEYSTORE_PASSWORD = "123456";
	    String KEY_PASSWORD = "123456";
	    ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PASSWORD.toCharArray());
	    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
	    kmf.init(ks, KEY_PASSWORD.toCharArray());
	    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
	    tmf.init(ks);
	    SSLContext sslContext = SSLContext.getInstance("TLS");  //SSLv3, TLS
//	    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
	    sslContext.init(kmf.getKeyManagers(), null, null);
	    return sslContext;
	  }
	public static void main(String[] args)  {
		HttpServerProvider provider = HttpServerProvider.provider();
//		HttpServer server =provider.createHttpServer(new InetSocketAddress(8082), 0);//监听端口8082	
		try {
//			HttpsServer server = provider.createHttpsServer(new InetSocketAddress(16790), 0);
		    HttpsServer server = HttpsServer.create(new InetSocketAddress(InetAddress.getByName("localhost"), 16790), 0);
			SSLContext sslContext;
			sslContext = MyHttpsServer.getSslContext();
			server.setHttpsConfigurator(new HttpsConfigurator(sslContext));
			MyHttpHandler handler = new MyHttpHandler();
			server.createContext("/", handler); 
			RechargeHandler recharge = new RechargeHandler();
			server.createContext("/recharge", recharge); 
			server.setExecutor(null);
			server.start();
			MyConst.log = MyLogger.getMylog();
			MyConst.log.info("fakeserver server started");
		} catch (Exception e) {
			MyConst.log.info("Failed to start fakeserver server:\n" + e);
			e.printStackTrace();
		}		

	}

}

MyHttpHandler请求处理

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.test.duliday.util.MyConst;
import com.test.duliday.util.MyJSON;
import com.test.duliday.util.MyRedis;
import com.test.duliday.util.MyString;
import com.test.duliday.util.ReturnObject;

public class MyHttpHandler implements HttpHandler {
	@Override
	public void handle(HttpExchange exchange) throws IOException {
		InputStream is = exchange.getRequestBody();	
		String response = "";
		//这里处理https请求,代码略
		is.close();              
        Headers headers = exchange.getResponseHeaders();        
        headers.set("Content-Type", "application/json; charset=utf-8"); 
        headers.set("Access-Control-Allow-Origin", "*");
        headers.set("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
        headers.set("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept"); 
        headers.set("Content-Type", "application/x-www-form-urlencoded");
               
        exchange.sendResponseHeaders(200, response.getBytes().length);       
        OutputStream os = exchange.getResponseBody();
        os.write(response.getBytes());
        os.close();
        }
}

运行

  1. 打包<MyHttpsServer.java> 和<MyHttpHandler.java> 为<fakeserver.jar>
  2. 启动服务 <MyHttpsServer.class>文件: java -jar fakeserver.jar
  3. 运行<SSLClient.java>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
假设我们有一个函数 `get_user_info`,它是一个本地函数,用于从数据库中检索用户信息。现在我们想要编写一个测试函数,来测试 `get_user_info` 函数的正确性,但是我们不想让测试函数真正去连接数据库。这个时候,我们可以使用mock来模拟 `get_user_info` 函数的行为。 首先,我们需要导入 `unittest` 和 `mock` 模块: ```python import unittest from unittest import mock ``` 接下来,我们可以定义一个测试类,并在其中编写测试函数: ```python class TestUserInfo(unittest.TestCase): def test_get_user_info(self): # 模拟一个数据库查询结果 mock_result = { 'name': 'Alice', 'age': 25, 'gender': 'female' } # 使用mock.patch装饰器来将get_user_info函数替换为一个mock对象 with mock.patch('__main__.get_user_info') as mock_get_user_info: # 当调用get_user_info时,返回模拟的查询结果 mock_get_user_info.return_value = mock_result # 调用被测试函数,并断言其结果是否正确 result = get_user_info('alice') self.assertEqual(result, mock_result) ``` 在测试函数中,我们首先使用 `mock.patch` 装饰器来将 `get_user_info` 函数替换为一个mock对象。然后,我们定义一个模拟的查询结果,并使用 `mock_get_user_info.return_value` 来让mock对象在调用时返回这个模拟结果。 最后,我们调用被测试函数 `get_user_info` 并断言其结果是否正确。 这样,我们就成功地使用mock来模拟了一个本地函数的行为,而不需要真正去连接数据库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值