接口自动化测试框架设计

news2024/12/25 13:11:11

文章目录

    • 接口测试的定义
    • 接口测试的意义
    • 接口测试的测试用例设计
    • 接口测试的测试用例设计方法
    • postman
      • 主要功能
      • 请求体分类
      • JSON数据类型
      • postman内置参数
      • postman变量
        • 全局变量
        • 环境变量
      • postman断言
      • JSON提取器
      • 正则表达式提取器
      • Cookie提取器
      • postman加密
      • 接口签名
    • 接口自动化测试基础
      • get
      • post-form
      • post-json
    • 接口自动化测试框架基础
      • 实现步骤
      • 使用步骤
      • 整体框架示意
      • 代码实现
        • com.edu.core
          • ApiListener.java
          • BaseTest.java
          • HttpDriver .java
          • MailUtil.java
        • com.edu.dataprovider
          • ExcelDataProvider.java
          • MysqlDataProvider.java
          • NSDataProvider.java
          • TxtDataProvider.java
        • com.edu.utils
          • Checker.java
          • Common.java
          • DbHelper.java
          • Log.java
          • ReadPro.java
          • ResultSetHandler.java
          • ResultVerifier.java
        • com.edu.test
          • LoginTest.java
        • src-log4j2.xml

接口测试的定义

测试系统间接口的一种测试,测试的对象主要是接口,主要是测试外部系统与所测试系统之间以及内部系统之间的交互点。

接口测试的意义

  • 前后端分离,通过测试保证服务端的正确性
  • 基于安全考虑,前端验证很容易跳过。
  • BUG更容易定位
  • 自动化测试落地性价比更高,比UI更稳定
  • 测试提前,降低研发成本,提高效率
  • 更容易实现持续集成

接口测试的测试用例设计

  • 功能
    • 功能是否正常
    • 功能是否按照接口文档实现
  • 逻辑业务
    • 是否依赖业务
  • 异常处理
    • 参数异常【关键字参数、参数为空、多或少参数、错误参数】
    • 数据异常【关键字数据、数据为空、长度不一致、错误数据】
  • 安全
    • Cookie
    • 传输数据是否加密
    • 身份权限验证
    • 密码规则是否符合需求
    • 唯一识别码

接口测试的测试用例设计方法

  • 等价类分析
  • 边界值分析法
  • 决策表
  • 场景法
    在这里插入图片描述

postman

主要功能

  • 模拟各种http requests
  • Collection功能
  • 人性化的Response整理
  • 内置测试脚本管理
  • 设定变量与环境

请求体分类

在这里插入图片描述

JSON数据类型

  • 数值【整数、浮点数】例:”price”:123.78
  • null空值【”“表示空字符串不是空值】 例:”name”:null
  • 逻辑值【true\false】 例:”student”:true
  • 对象【花括号】例:”address”:{“line”: 123 yuhua road”,“city”:”shijiazhuang”}
  • 数组【方括号】例:“employees”: [{ “firstName”:“Bill” , “lastName”:“Gates” }, {“firstName”:“George” , “lastName”:“Bush” }]

postman内置参数

https://learning.postman.com/docs/writing-scripts/script-references/variables-list/

  • 时间戳:{{KaTeX parse error: Expected 'EOF', got '}' at position 10: timestamp}̲} {"tag":{"name…timestamp}}"}}
  • 随机生成整数0~1000:{{KaTeX parse error: Expected 'EOF', got '}' at position 10: randomInt}̲} {"tag":{"id":…randomInt}}"} }
  • 生成随机的GUID的字符串:{{KaTeX parse error: Expected 'EOF', got '}' at position 5: guid}̲} { "tag" : { …guid}}" } }

postman变量

全局变量

全局变量可供所有请求使用
pm.globals.set(“token1”, jsonData.access_token);

环境变量

//提取token的值
var jsonData=JSON.parse(responseBody)
console.log(jsonData.access_token)
pm.environment.set(“token1”, jsonData.access_token);

postman断言

在这里插入图片描述
在这里插入图片描述

JSON提取器

在这里插入图片描述

正则表达式提取器

在这里插入图片描述

Cookie提取器

在这里插入图片描述

postman加密

常见加密方式三种方式:

  • 加密算法(MD5、RSA、DES、AES、SHA)
  • 自定义加密算法
  • 接口签名
    在这里插入图片描述

接口签名

  • 1什么是接口签名?
  • 使用用户名,密码,时间戳和所有的排过序之后的参数,拼接组合起来成为一个串,再把该串加密得到的字符串,这就是一个签名。该签名字符串是唯一的有权访问第三方接口的鉴权码。
  • 2为什么需要做接口签名?
  • 防篡防伪装攻击。
  • 改攻击。
  • 防重放攻击。
  • 防数据泄露 。
  • 3生成signature(签名)规则
  • 对所有请求参数按key的ASCII码做升序排列
  • 把请求参数拼接组合成串
  • 把AccessKey和SecretKey码加入上面拼接好的字符串
  • 用时间戳连接到字符串的尾部
  • 再把这个字符串进行MD5加密,加密后再转化成大写
    在这里插入图片描述
    在这里插入图片描述

接口自动化测试基础

get

  • 创建HttpClient对象
  • CloseableHttpClient client =HttpClient.createDefault();
  • 创建get请求对象
  • HttpGet get=new HttpGet(url);
  • 执行请求获取响应
  • CloseHttpResponse response=client.execute(get)
  • 获得响应体
  • HttpEntity response_entity=response.getEntity();
  • 获取响应体内容
  • String response_str=EntityUtils.toString(response_entity,"utf-8");
  • 释放资源
  • EntityUtils.consume(entity);
  • 关闭连接
  • response.close();client.close();

post-form

  • 创建HttpClient对象
  • CloseableHttpClient client =HttpClient.createDefault();
  • 创建post请求
  • HttpPost post=new HttpPost(url);
  • 设置请求头
  • post.setHeader(Content-Type","application/x-www-form-url")
  • 构建请求体
  • List<NameValuePair> user=new ArrayList<>() user.add(new BasicNameValuePair("username","vip") user.add(new BasicNameValuePair("password","secret") ;
    HttpEntity user=new StringEntity(“username=vip&password=secret”)
  • 设置请求实体
  • post.setEntity(new UrlEncodedFormEntity(user));
    post.setEntity(user)
  • 执行请求获取响应
  • CloseHttpResponse response=client.execute(post)
  • 获得响应体
  • HttpEntity response_entity=response.getEntity();
  • 获取响应体内容
  • String response_str=EntityUtils.toString(response_entity,"utf-8");

post-json

  • 使用fastjson构建请求体
  • JSONObject user=new JSONObject() user.put(" "," ");
  • 设置请求实体
  • post.setEntity

接口自动化测试框架基础

实现步骤

1.域名存放在属性文件中
2.常用get,post,方法进行封装,针对不同的参数,实现重载。
doGet(String url)
doGet(String url,Map<String,Object> para)
doGetByCookie(String url,CookieStore cookie)
doPost(String url,String para)
doPostByForm(String url, List data )针对Content-type是Form
doPost(String url,JSONObject para) 针对Content-type是JSON
doPostByCookie(String url,JSONObject para,CookieStore cookie)
3.断言的封装 Checker
4.数据驱动(把1000个商品遍历,做submit的操作;10个用户的登录,下单)
5.数据库的访问(JDBC)
6.监听器的使用
ApiListener extends TestListenerAdapter
重写 onFinish()方法
7.发送邮件 JAVAMail

使用步骤

1.创建空项目 Qg
2.创建libs,把需要的jar拷贝进来
3.拷贝conf目录
4.拷贝log4j2.xml文件
5.每个接口创建一个测试类
6.对接口的操作封装为方法
7.如果需要数据库的验证,测试类需要继承
BaseTest

整体框架示意

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

代码实现

com.edu.core
ApiListener.java
package com.edu.core;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

import com.edu.utils.Log;
import com.edu.utils.ReadPro;

public class ApiListener extends TestListenerAdapter {

	private String writeResultToMail() {
		ITestNGMethod method[] = this.getAllTestMethods();
		List failedList = this.getFailedTests();
		List passedList = this.getPassedTests();
		List failedList1 = new ArrayList();
		List passedList1 = new ArrayList();
		for (int j = 0; j < failedList.size(); j++) {

			ITestResult tr = (ITestResult) failedList.get(j);
			if (tr.getMethod().getDescription() != null) {
				tr.setAttribute("name", tr.getMethod().getDescription());
			} else {
				tr.setAttribute("name", "");
			}

			failedList1.add(tr);
		}
		for (int j = 0; j < passedList.size(); j++) {
			ITestResult tr = (ITestResult) passedList.get(j);
			if (tr.getMethod().getDescription() != null) {
				tr.setAttribute("name", tr.getMethod().getDescription());
			} else {
				tr.setAttribute("name", "");
			}

			passedList1.add(tr);
		}
		Map context = new HashMap();
		context.put("date", new Date());
		context.put("failedList", failedList.size());
		context.put("passedList", passedList1.size());
		context.put("casesize", passedList.size() + failedList.size());
		context.put("failcasesize", failedList.size());
		try {

			String content = mapToString(context);
			return content;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static String mapToString(Map<String, Object> para) {

		StringBuilder sBuilder = new StringBuilder();
		int size = para.size();
		for (Entry<String, Object> entry : para.entrySet()) {
			sBuilder.append(entry.getKey() + "=" + entry.getValue() + "\n");

		}

		return sBuilder.toString();

	}

	@Override
	public void onFinish(ITestContext testContext) {

		super.onFinish(testContext);
		System.out.println(getAllTestMethods().length);
		String emailContent = this.writeResultToMail();
		System.out.println(emailContent);

		String emailTitle = ReadPro.getPropValue("mail_title") + "----" + this.getTime();
		String toMail = ReadPro.getPropValue("to_mail");
		try {
//			System.out.println(emailContent);
//			MailUtil.sendEmail(toMail, emailTitle, emailContent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public String getTime() {
		java.util.Calendar c = java.util.Calendar.getInstance();
		java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("yyyy-MM-dd  hh:mm:ss");
		return f.format(c.getTime());
	}

//	@Override
//	public void onTestSuccess(ITestResult tr) {
//		Log.info(tr.getInstance() + "-" + tr.getName() + "运行成功");
//	}
//
//	@Override
//	public void onTestFailure(ITestResult tr) {
//
//		Log.error(tr.getInstance() + "-" + tr.getName() + "运行失败");
//	}

}


BaseTest.java
package com.edu.core;

import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;

import com.edu.utils.DbHelper;

public class BaseTest {
	public DbHelper db ;
	
	@BeforeClass
	public void setUp()	throws Exception {
		db=DbHelper.getInstance();
		System.out.println("初始化数据库");
		
  }

	@AfterClass
	public void tearDown() throws Exception {
		
		db.close();
	}

}


HttpDriver .java
package com.edu.core;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

import com.alibaba.fastjson2.JSONObject;
import com.edu.utils.Common;
import com.edu.utils.ReadPro;



public class HttpDriver {
	static CloseableHttpClient httpClient = null;
	static CloseableHttpResponse respone = null;

	public static String doGet(String url) throws Exception {
		httpClient = HttpClients.createDefault();
		HttpGet get = new HttpGet(ReadPro.getPropValue("base_url") + url);
	
		respone = httpClient.execute(get);
		HttpEntity entity = respone.getEntity();
		String content = EntityUtils.toString(entity, "utf-8");
		EntityUtils.consume(entity);
		respone.close();
		httpClient.close();
		return content;
	}

	public static String doGet(String url, JSONObject data) throws Exception {
		String para = URLEncoder.encode(data.toString(), "UTF-8");
		httpClient = HttpClients.createDefault();
		HttpGet get = new HttpGet(url + "?" + para);
		respone = httpClient.execute(get);
		HttpEntity entity = respone.getEntity();
		String content = EntityUtils.toString(entity, "utf-8");
		EntityUtils.consume(entity);
		respone.close();
		httpClient.close();
		return content;
	}

	
	public static String doGetForEncoder(String url, String para) throws Exception {
		httpClient = HttpClients.createDefault();
		String content=URLEncoder.encode(para,"utf-8");
		HttpGet get = new HttpGet(ReadPro.getPropValue("base_url") + url + content);
		respone = httpClient.execute(get);
		HttpEntity entity = respone.getEntity();
		String result = EntityUtils.toString(entity, "utf-8");
		EntityUtils.consume(entity);
		respone.close();
		httpClient.close();
		return result;
	}



	public static String doGet(String url, Map<String, String> para) throws IOException, ParseException {
		String content = null;
		httpClient = HttpClients.createDefault();
		HttpGet get = new HttpGet(ReadPro.getPropValue("base_url") + url + "?" +Common.mapToString(para));
		respone = httpClient.execute(get);
		HttpEntity entity = respone.getEntity();
		content = EntityUtils.toString(entity, "utf-8");
		EntityUtils.consume(entity);
		respone.close();
		httpClient.close();
		return content;
	}

	public static String doPost(String url, JSONObject para) {
		httpClient = HttpClients.createDefault();
		HttpPost post = new HttpPost(ReadPro.getPropValue("base_url") + url);
		post.addHeader("Content-Type", "application/json");
		HttpEntity data;
		String content = null;
		try {
			data = new StringEntity(para.toString());

			post.setEntity(data);
			respone = httpClient.execute(post);

			HttpEntity entity = respone.getEntity();
			content = EntityUtils.toString(entity, "utf-8");
			EntityUtils.consume(entity);

			respone.close();
			httpClient.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return content;

	}

	public static String doGet(String url, CookieStore cookie) throws Exception {

		CloseableHttpClient client=HttpClients.custom()
				.setDefaultCookieStore(cookie).build();
		HttpGet get = new HttpGet(ReadPro.getPropValue("base_url") + url);
		CloseableHttpResponse response = client.execute(get);
		HttpEntity result_entity = response.getEntity();
		String result = EntityUtils.toString(result_entity, "utf-8");
		EntityUtils.consume(result_entity);
		response.close();
		client.close();
		return result;
	}




	public static String doPostByForm(String url, List<NameValuePair> data ) throws Exception {
		httpClient = HttpClients.createDefault();
		HttpPost post = new HttpPost(ReadPro.getPropValue("base_url") + url);
		post.addHeader("Content-Type", "application/x-www-form-urlencoded");

		post.setEntity(new UrlEncodedFormEntity(data));
		respone = httpClient.execute(post);

		HttpEntity entity = respone.getEntity();
		String content = EntityUtils.toString(entity, "utf-8");

		respone.close();
		httpClient.close();

		return content;

	}



	
	public static String doPost(String url, JSONObject para, CookieStore cookie) throws Exception {
			httpClient=HttpClients.custom()
								.setDefaultCookieStore(cookie).build();
		HttpPost post = new HttpPost(ReadPro.getPropValue("base_url")+url);
		post.addHeader("Content-Type", "application/json");
		HttpEntity data = new StringEntity(para.toString());
		post.setEntity(data);
		CloseableHttpResponse respone = httpClient.execute(post);
		HttpEntity entity = respone.getEntity();
		String content = EntityUtils.toString(entity, "utf-8");
		EntityUtils.consume(entity);
		respone.close();
		httpClient.close();
		return content;

	}

}


MailUtil.java
package com.edu.core;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class MailUtil {
	static int port = 25;

    static String server = "smtp.126.com";
    static String from = "李焕贞";
    static String user = "testlihuanzhen@126.com";
    static String password = "123456abcd";//授权码

   
    public static void sendEmail(String email, String subject, String body) throws UnsupportedEncodingException {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", server);
            props.put("mail.smtp.port", String.valueOf(port));
            props.put("mail.smtp.auth", "true");
            Transport transport = null;
            Session session = Session.getDefaultInstance(props,null);
            transport = session.getTransport("smtp");
            transport.connect(server, user, password);
            MimeMessage msg = new MimeMessage(session);
            msg.setSentDate(new Date());
            
            InternetAddress fromAddress = new InternetAddress(user,from,"UTF-8");
            msg.setFrom(fromAddress);
            String emailList[]=email.split(",");
            InternetAddress[] toAddress = new InternetAddress[emailList.length];
            
            for(int i=0;i<emailList.length;i++)
            {
            	toAddress[i]=new InternetAddress(emailList[i]);
            }
          
            msg.addRecipients(Message.RecipientType.TO, toAddress);
            msg.setSubject(subject, "UTF-8");   
            msg.setContent(body, "text/html;charset=utf-8");
            msg.saveChanges();
            transport.sendMessage(msg, msg.getAllRecipients());
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    public static void main(String args[]) throws UnsupportedEncodingException
    {
    	
    	MailUtil.sendEmail("testlihuanzhen@126.com", "星期二", "测试");
    }


}


com.edu.dataprovider
ExcelDataProvider.java
package com.edu.dataprovider;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/*
 * Excel数据驱动类
 */

public class ExcelDataProvider {



	public Object[][] getTestDataByExcel(String fileName, String sheetName)
			throws IOException {
		File file = new File(fileName);
		FileInputStream inputstream = new FileInputStream(file);
		Workbook wbook = null;
		String fileExtensionName = fileName.substring(fileName.indexOf("."));
	
		if (fileExtensionName.equals(".xlsx")) {
			wbook = new XSSFWorkbook(inputstream);
		
		} else if (fileExtensionName.equals(".xls")) {
			wbook = new HSSFWorkbook(inputstream);
		}
		Sheet sheet = wbook.getSheet(sheetName);
		// 通过sheetName生成Sheet对象
		int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
		// 获取当前sheet行数,行号和列号都是从0开始
		List<Object[]> records = new ArrayList<Object[]>();
		// 使用双循环获取excel文件的所有数据(第一行除外)
		for (int i = 1; i < rowCount + 1; i++) {
			Row row = sheet.getRow(i);
			String fields[] = new String[row.getLastCellNum()];
			for (int j = 0; j < row.getLastCellNum(); j++) {
				// 获取单元格数据
				fields[j] = row.getCell(j).getStringCellValue();
			}
			records.add(fields);
		}
		Object[][] results = new Object[records.size()][];
		for (int i = 0; i < records.size(); i++) {
			results[i] = records.get(i);
		}
		return results;
	}
	

}


MysqlDataProvider.java
package com.edu.dataprovider;

import java.io.IOException;
import java.sql.*;

import java.util.ArrayList;
import java.util.List;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class MysqlDataProvider {
	

	
	public  Object[][] getTestDataByMysql(String sql) {
		String url = "jdbc:mysql://10.7.90.21:3306/market_db";
		List<Object[]> records = new ArrayList<Object[]>();

		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager
					.getConnection(url, "root", "123456");
			if (!conn.isClosed()) {
				System.out.println("连接数据库成功");
			}
			// Statement里面带有很多方法,比如executeUpdate可以实现插入,更新和删除等
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			//得到数据集的结构
			ResultSetMetaData rsMetaData = rs.getMetaData();
			int cols = rsMetaData.getColumnCount();
			System.out.println(cols);
			while (rs.next()) {
				String fields[] = new String[cols];

				int col=0;
				for (int i = 0; i < cols; i++) {
					fields[col] = rs.getString(i+1);//读取当前行指定的列
					col++;
				}
				records.add(fields);
			
			}
			rs.close();
			conn.close();

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Object[][] results = new Object[records.size()][];
		for (int i = 0; i < records.size(); i++) {
			results[i] = records.get(i);
		}
		return results;
	}


}


NSDataProvider.java
package com.edu.dataprovider;

import java.io.IOException;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class NSDataProvider {

	@DataProvider(name="goodId")
	public Object[][] getId() throws IOException{
		return new ExcelDataProvider()
				.getTestDataByExcel("data/mall.xlsx", 
						"Sheet1");
	}
	
	@Test(dataProvider ="goodId" )
	public void test1(String id) {
		System.out.println(id);
	}
	
	@DataProvider(name="zl_shop")
	public  Object[][] getTxtData() throws IOException{
		return new  TxtDataProvider().getTxtUser("data/user.txt");
	}
	@DataProvider(name="user")
	public  Object[][] getMovieData() throws IOException{
		return new  ExcelDataProvider().getTestDataByExcel("data/user.xlsx","Sheet1");
	}
	@Test(dataProvider="txt")
	public void getData(String a,String b) {
		System.out.println(a+" "+b);
		
	}

	@DataProvider(name="excel")
	public Object[][] getExcelDada() throws IOException{
		return new ExcelDataProvider().getTestDataByExcel("data/user.xlsx","Sheet1");
	}
	
	@DataProvider(name="mysql")
	public Object[][] getMysqlDada() throws IOException{
		return new MysqlDataProvider().getTestDataByMysql
				("SELECT pid,name from t_product");
	}
	
	@Test(dataProvider="mysql")
	public void testDB(String a,String b) {
		System.out.println(a+" "+b);
	}
	
}


TxtDataProvider.java
package com.edu.dataprovider;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TxtDataProvider {
	
	
	public Object[][] getTxtUser(String fileName) throws IOException {
		
		List<String> dataList = new ArrayList<String>();
	
		File file = new File(fileName);
		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr= new InputStreamReader(fis);
		BufferedReader reader = new BufferedReader(isr);
		int cols=reader.readLine().split("\t").length;
		
		String readData;
		while((readData=reader.readLine())!=null) {
			dataList.add(readData);
		}
		
		Object [][] result = new Object[dataList.size()][cols];
		String [] arrays;
		for(int i=0;i<dataList.size();i++) {
			arrays=dataList.get(i).split("\t");
			for(int j=0;j<cols;j++)
				result[i][j]=arrays[j];
		}
		return result;
		
	}


	

}


com.edu.utils
Checker.java
package com.edu.utils;

import static org.testng.Assert.assertEquals;

import java.util.List;

import com.alibaba.fastjson2.JSONObject;




public class Checker {
	
	String exceptionMessage = "";

	String message = "";

	String actualValue = "";

	String expectValue = "";
	JSONObject json = null;

	public Checker(String result) {
		this.json = JSONObject.parseObject(result);
	}

	public void assertArray(String patten,String key,String content){
		actualValue=this.json.getJSONArray(patten).getJSONObject(0).getString(key);
	assertEquals(actualValue, content);
	}

	public void verifyTextPresent(String patten) throws Exception {

		boolean value = json.containsKey(patten);

		if (value) {
			Log.info("the Text: '" + patten + "' is Present!");
		} else {
			Log.fatal("the Text: '" + patten + "' is not Present!");
			throw new Exception("the Text: '" + patten + "' is not Present!");
		}
	}

	public void verifyXpath(String locator, String patten) throws Exception {

		actualValue = this.json.getString(locator);
		verify(patten, actualValue);
	}


	

	public void verify(String pattern, String actualValue) throws Exception {
		this.actualValue = actualValue;
		this.setExceptionMessage(actualValue, pattern);
		this.setMessage(pattern, actualValue);
		String errormsg = getExceptionMessage();
		String msg = getMessage();
		if (ResultVerifier.verifyStringsByEqualAndExist(pattern, actualValue)) {
			Log.info(msg);
		} else {
			Log.fatal(errormsg);
			Log.info(json.toString());
			throw new Exception(errormsg);
		}
	}
	
	public void assertXpath(String locator, String object) throws Exception {
		// TODO Auto-generated method stub
		actualValue = this.json.getString(locator);
		assertEquals(actualValue,object);
	}
	
	public void setExceptionMessage(String actualValue, String expectValue) {
		this.exceptionMessage = "expectedValue doesn't match actualValue,actual Value is :" + actualValue
				+ "; expected Value is :" + expectValue;
	}

	public void setMessage(String expectValue, String actualValue) {
		this.message = "expectedValue :" + expectValue + "  match actualValue:" + actualValue;
	}

	public String getExceptionMessage() {
		return exceptionMessage;
	}

	public String getMessage() {
		return message;
	}
}


Common.java
package com.edu.utils;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.cookie.BasicCookieStore;
import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

import com.alibaba.fastjson2.JSONObject;



public class Common {
	// 把map类型转换为String,并用&加以拼接
	public static String mapToString(Map<String, String> para) {

		StringBuilder sBuilder = new StringBuilder();
		String content = null;
		int size = para.size();
		for (Entry<String, String> entry : para.entrySet()) {
			sBuilder.append(entry.getKey() + "=" + entry.getValue());
			size--;
			if (size >= 1) {
				sBuilder.append("&");
			}

		}
		return sBuilder.toString();
	}
	
	
	public static CookieStore getCookie(String u_name,String password) throws Exception, IOException {
		JSONObject user=new JSONObject();
		user.put("phoneArea", "86");
		user.put("phoneNumber", u_name);
		user.put("password", password);
		
		
		CookieStore cookie = new BasicCookieStore();

		CloseableHttpClient client = HttpClients.
				custom().
				setDefaultCookieStore(cookie)
				.build();
		
		String loginurl=ReadPro.getPropValue("base_url")+"/common/fgadmin/login";
		HttpPost post =new HttpPost(loginurl);
		//设置请求体
		HttpEntity userEntity=new StringEntity(user.toString());
		post.setHeader("Content-Type","application/json");
		post.setEntity(userEntity);
		CloseableHttpResponse response=client.execute(post);
		HttpEntity responseEntity=response.getEntity();
		String result=EntityUtils.toString(responseEntity,"UTF-8");
		System.out.println(result);
		EntityUtils.consume(responseEntity);
		response.close();
		client.close();
	
		return cookie;
		
		
	}

}


DbHelper.java
package com.edu.utils;


import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//import java.sql.DriverManager;
//import java.sql.PreparedStatement;
//import java.sql.ResultSet;
//import java.sql.SQLException;
//import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class DbHelper {
	static Logger log = LogManager.getLogger(DbHelper.class.getName());
	
	public java.sql.Connection conn = null; //connection object
	public ResultSet rs = null; //resultset object
	public Statement stmt = null; //statement object
	public PreparedStatement pstmt = null; //preparedstatement object
	private String drivers = null; //connection parameter:drivers
	private String url = null; //connection parameter:url
	private String user = null; //connection parameter:user
	private String password = null; //connection parameter:password
	private String configFile;

	public DbHelper() {

	}

	public DbHelper(String configFile) {
		this.configFile = configFile;
		init();
	}

	public static DbHelper getInstance() {
		DbHelper instance = new DbHelper("conf/conf.properties");
		instance.init();
		return instance;
	}

	private void init() {
		drivers = ReadPro.getPropValue("persistence.datasource.driverClassName");
		url = ReadPro.getPropValue("persistence.datasource.url");
		user = ReadPro.getPropValue("persistence.datasource.username");
		password = ReadPro.getPropValue("persistence.datasource.password");
		try {
			log.info(drivers+"---"+url);
			Class.forName(drivers);
			conn = DriverManager.getConnection(url, user, password);
			stmt = conn.createStatement();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public List query(String sql) throws Exception{
		List list = null;
		rs = stmt.executeQuery(sql);
		if (null != rs) {
			list = ResultSetHandler.toMapList(rs);
		}
		return list;
	}
	
	public boolean execute(String sql) throws Exception{
		boolean flag=false;
		flag = stmt.execute(sql);
		return flag;
	}

	public Map queryToMap(String sql) throws Exception{
		Map map = null;
		rs = stmt.executeQuery(sql);
		if (null != rs) {
			map = ResultSetHandler.toMap(rs);
		}
		return map;
	}

	public List queryToList(String sql) throws Exception {
		List list = null;
		rs = stmt.executeQuery(sql);
		if (null != rs) {
			list = ResultSetHandler.toStringArrayList(rs);
		}
		return list;
	}

	public String queryToString(String sql) { 
		String str = null;
		try {
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (null != rs) {
			try {
				str = ResultSetHandler.toString(rs);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return str;
	}

	public void close() {
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException ex) {
				rs = null;
			}
		}
		if (null != stmt) {
			try {
				stmt.close();
			} catch (SQLException ex) {
				stmt = null;
			}
		}
		if (null != pstmt) {
			try {
				pstmt.close();
			} catch (SQLException ex) {
				pstmt = null;
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				conn = null;
			}

		}
	}

	public static void main(String args[]) {
		DbHelper db = DbHelper.getInstance();
		try {
			List list = db.query("select * from malluser");
			for (int i = 0; i < list.size(); i++) {
				HashMap map = (HashMap) list.get(i);
				System.out.println(map.toString());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}


Log.java
package com.edu.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log {
	static Logger logger = LogManager.getLogger(Log.class);


	public static void fatal(String msg) {
		logger.fatal(msg);
	}

	public static void error(String msg) {
		logger.error(msg);
	}

	public static void warn(String msg) {
		logger.warn(msg);
	}

	public static void info(String msg) {
		logger.info(msg);
	}

	public static void debug(String msg) {
		logger.debug(msg);
	}
}


ReadPro.java
package com.edu.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;


public class ReadPro {

	public static final String filePath="conf/conf.properties";
	

	public static String getPropValue(String key) {
		Properties prop = new Properties();
		FileInputStream fis;
		try {
			fis = new FileInputStream(filePath);
			prop.load(fis);
			fis.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return prop.getProperty(key);
		
	}
}


ResultSetHandler.java
package com.edu.utils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;





public class ResultSetHandler {
	
	static Logger log = LogManager.getLogger(ResultSetHandler.class.getName());
    public static List<Map<String, String>> toMapList(ResultSet rs)
    {
        List<Map<String, String>> lst = new ArrayList<Map<String, String>>();
        ResultSetMetaData md;
        try
        {
            md = rs.getMetaData();
            String[] fieldNames = new String[md.getColumnCount()];
            for(int i=1;i<=fieldNames.length;i++)
            {
                fieldNames[i-1] = md.getColumnLabel(i).toLowerCase();
            }
            while(rs.next())
            {
                Map<String, String> map = new HashMap<String, String>();
                for (int i = 1; i <= fieldNames.length; i++) 
                {
                	if(8==md.getColumnType(i))
                	{
                		map.put(fieldNames[i-1],String.valueOf(rs.getDouble(i)));
                	}else
                	{
                		map.put(fieldNames[i-1],rs.getString(i));
                	}
                    
                }
                lst.add(map);
            }
        }
        catch (Exception e)
        {
            log.error(e.getMessage(),e);
            //throw(new BaseException(Errors.ERRORS_COMMON,new String[]{Errors.DBOPERATION_FORMATRESULT},e.getMessage(),e));
        }
        return lst;
    }
    
    //private static Logger log = Logger.getLogger(ResultSetHandler.class);

    public static Map<String, String> toMap(ResultSet rs)
    {
    	Map<String, String> map = new HashMap<String, String>();
        ResultSetMetaData md;
        try
        {
            md = rs.getMetaData();
            String[] fieldNames = new String[md.getColumnCount()];
            for(int i=1;i<=fieldNames.length;i++)
            {
                fieldNames[i-1] = md.getColumnLabel(i).toLowerCase();
            }
            if(rs.next())
            {
                for (int i = 1; i <= fieldNames.length; i++) 
                {
                	if(8==md.getColumnType(i))
                	{
                		map.put(fieldNames[i-1],String.valueOf(rs.getDouble(i)));
                	}else
                	{
                		map.put(fieldNames[i-1],rs.getString(i));
                	}
                }
            }
        }
        catch (Exception e)
        {
            log.error(e.getMessage(),e);
            //throw(new BaseException(Errors.ERRORS_COMMON,new String[]{Errors.DBOPERATION_FORMATRESULT},e.getMessage(),e));
        }
        return map;
    }
 
    public static List toStringArrayList(ResultSet rs) throws Exception
    {
        List<String[]> lst = new ArrayList<String[]>();
        ResultSetMetaData md = rs.getMetaData();
        int fieldCount = md.getColumnCount();
        while(rs.next())
        {
            String[] arr = new String[fieldCount];
            for (int i = 1; i <= fieldCount; i++) 
            {
                arr[i-1] = rs.getString(i);
            }
            lst.add(arr);
        }
        return lst;
    }
    
  
    public static String toString(ResultSet rs) throws Exception
    {
    	String str = "";
        ResultSetMetaData md = rs.getMetaData();
        int fieldCount = md.getColumnCount();
        if(rs.next()&&fieldCount>=1)
        {           
        	if(8==md.getColumnType(1))
        	{
        		str = String.valueOf(rs.getDouble(1));
        	}else
        	{
        		str = rs.getString(1);
        	}
        	
        }
        return str;
    }
  
    public static List<Object[]> toObjectArrayList(ResultSet rs)
    {
        List<Object[]> lst = new ArrayList<Object[]>();
        ResultSetMetaData md;
        try
        {
            md = rs.getMetaData();
            int fieldCount = md.getColumnCount();
            while(rs.next())
            {
                Object[] arr = new Object[fieldCount];
                for (int i = 1; i <= fieldCount; i++) 
                {
                    arr[i-1] = rs.getObject(i);
                }
                lst.add(arr);
            }        }
        catch (SQLException e)
        {
            //log.error(e.getMessage(),e);
            //throw(new BaseException(Errors.ERRORS_COMMON,new String[]{Errors.DBOPERATION_FORMATRESULT},e.getMessage(),e));
        }
        return lst;
    }
    
    public List<String> getFieldList(ResultSet rs) 
    {
        ResultSetMetaData md;
        List<String> list = null;
        try
        {
            md = rs.getMetaData();
            list = new ArrayList<String>();
            for(int i=1;i<=md.getColumnCount();i++)
            {
                list.add(md.getColumnLabel(i).toLowerCase());
            }
        }
        catch (SQLException e)
        {
            log.error(e.getMessage(),e);
           
        }
        
        return list;
    }
}



ResultVerifier.java
package com.edu.utils;



public class ResultVerifier {


    public static boolean verifyStringsByEqual(final String expectedValue, final String actualValue) {
		return expectedValue != null && expectedValue.equals(actualValue);
	}
    
    public static boolean verifyStringsByEqualAndExist(final String expectedValue, final String actualValue) {
		boolean flag=false;
    	if(expectedValue != null && expectedValue.equals(actualValue))
		{
    		flag=true;
    		return flag;
		}
    	if(expectedValue != null && actualValue.contains(expectedValue))
    	{
    		flag=true;
    		return flag;
    	}
    	return flag;
	}
    public static void main(String args[])
    {
    	System.out.print(ResultVerifier.verifyStringsByEqualAndExist("hello", "hello world"));

    }
}
com.edu.test
LoginTest.java
package com.edu.test;


import org.testng.annotations.Test;

import com.alibaba.fastjson2.JSONObject;
import com.edu.core.ApiListener;
import com.edu.core.HttpDriver;
import com.edu.dataprovider.NSDataProvider;
import com.edu.utils.Checker;




public class LoginTest {
	String login_url = "/common/fgadmin/login";
	Checker check = null;

	public void login(Object phoneArea, Object phoneNumber, Object password) {
		JSONObject user = new JSONObject();
		user.put("phoneArea", phoneArea);
		user.put("phoneNumber", phoneNumber);
		user.put("password", password);
		String result = HttpDriver.doPost(login_url, user);
		System.out.println(result);
		check = new Checker(result);
	}

	
	@Test
	public void testLoginSuccess() throws Exception {
		login("86", "2000", "123456");
		check.verifyTextPresent("message");
		check.verifyXpath("code", "200");
	}

	

}


src-log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
	<Appenders>
	
		<Console name="Console" target="SYSTEM_ERR">
			<PatternLayout pattern="[%-5p] %d %c - %m%n" />
		</Console>
		<File name="File" fileName="dist/my.log">
			<PatternLayout pattern="[%-5p] %d %c - %m%n" />
		</File>
	</Appenders>
	<Loggers>
		<Root level="WARN">
			<AppenderRef ref="File" />
			<AppenderRef ref="Console" />
		</Root>
	</Loggers>
</Configuration>


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1395385.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

JVM实战(28)——模拟Metaspace内存溢出

作者简介&#xff1a;大家好&#xff0c;我是smart哥&#xff0c;前中兴通讯、美团架构师&#xff0c;现某互联网公司CTO 联系qq&#xff1a;184480602&#xff0c;加我进群&#xff0c;大家一起学习&#xff0c;一起进步&#xff0c;一起对抗互联网寒冬 学习必须往深处挖&…

15.云原生之k8s容灾与恢复实战

云原生专栏大纲 文章目录 Velero与etcd介绍Velero与etcd备份应用场景Velero与etcd在k8s备份上的区别 Velero备份恢复流程备份工作流程Velero备份时&#xff0c;若k8s集群发送变化&#xff0c;会发发生情况&#xff1f;Velero 备份pv&#xff0c;pv中数据变化&#xff0c;会发发…

C++ //练习 1.25 借助网站上的Sales_item.h头文件,编译并运行本节给出的书店程序。

C Primer&#xff08;第5版&#xff09; 练习 1.25 练习 1.25 借助网站上的Sales_item.h头文件&#xff0c;编译并运行本节给出的书店程序。 环境&#xff1a;Linux Ubuntu&#xff08;云服务器&#xff09; 工具&#xff1a;vim 代码块 /********************************…

Flutter中使用minio_new库

前言 在移动开发中&#xff0c;我们常常会遇到需要在App中处理文件上传和下载的需求。Minio是一个开源的对象存储服务&#xff0c;它兼容Amazon S3云存储服务接口&#xff0c;可以用于存储大规模非结构化的数据。 开始之前 在pubspec.yaml文件中添加minio_new库的依赖&#xf…

最终Docker6:nacos集群部署

目录 mysql容器构建 1.进入soft 文件夹&#xff0c;创建mysql文件夹 2.进入conf文件夹 放入my.conf 配置文件 3.运行mysql容器 4.进入script文件夹 导入 sql文件 5.进入mysql 容器 并登录 6.创建nacos 数据库并使用&#xff0c;运行nacos.sql文件 7.授予用户所有权限 部…

loading stable diffusion model: FileNotFoundError解决方案

大家好&#xff0c;我是水滴~~ 本文主要介绍在安装 stable-diffusion-webui 时出现的 loading stable diffusion model: FileNotFoundError 问题的解决方案&#xff0c;希望能对你有所帮助。 文章目录 问题描述解决方案 问题描述 在安装 stable-diffusion-webui 过程中出现 l…

Linux环境下,针对QT软件工程搭建C++Test单元测试环境的操作指南

文章目录 前言一、安装QT二、安装CTest三、使用QT生成.bdf文件四、创建CTest工程注意事项 前言 CTest是Parasoft公司出品的一款可以针对C/C源代码进行静态分析、单元测试、集成测试的测试工具。本文主要讲解如何在Linux环境下&#xff0c;搭建QT插件版的CTest测试环境。 一、…

大数据开发之Hadoop(优化新特征)

第 1 章&#xff1a;HDFS-故障排除 注意&#xff1a;采用三台服务器即可&#xff0c;恢复到Yarn开始的服务器快照。 1.1 集群安全模块 1、安全模式&#xff1a;文件系统只接收读数据请求&#xff0c;而不接收删除、修改等变更请求 2、进入安全模式场景 1&#xff09;NameNod…

GPT应用开发:GPT插件开发指南

欢迎阅读本系列文章&#xff01;我将带你一起探索如何利用OpenAI API开发GPT应用。无论你是编程新手还是资深开发者&#xff0c;都能在这里获得灵感和收获。 本文&#xff0c;我们将继续展示聊天API中插件的使用方法&#xff0c;让你能够轻松驾驭这个强大的工具。 插件运行效…

记一次 .NET某道闸收费系统 内存溢出分析

一&#xff1a;背景 1. 讲故事 前些天有位朋友找到我&#xff0c;说他的程序几天内存就要爆一次&#xff0c;不知道咋回事&#xff0c;找不出原因&#xff0c;让我帮忙看一下&#xff0c;这种问题分析dump是最简单粗暴了&#xff0c;拿到dump后接下来就是一顿分析。 二&…

移动web开发流式布局

1.0 移动端基础 1.1 浏览器现状 PC端常见浏览器&#xff1a;360浏览器、谷歌浏览器、火狐浏览器、QQ浏览器、百度浏览器、搜狗浏览器、IE浏览器。 内核&#xff1a; 浏览器内核备注Safariwebkitwebkit内核是苹果公司开发的一款渲染引擎&#xff0c;目前已被很多手机厂商所采…

Java开发的审批流系统,前端使用vue,支持常态化工作审批流程

一、项目形式 springbootvueactiviti集成了activiti在线编辑器&#xff0c;快速开发平台&#xff0c;可插拔工作流服务。 二、项目介绍 本项目拥有用户管理&#xff0c;部门管理&#xff0c;代码生成&#xff0c;系统监管&#xff0c;报表&#xff0c;大屏展示&#xff0c;业…

文心一言使用分享

ChatGPT 和文心一言哪个更好用&#xff1f; 一个直接可以用&#xff0c;一个还需要借助一些工具&#xff0c;还有可能账号会消失…… 没有可比性。 通用大模型用于特定功能的时候需要一些引导技巧。 import math import time def calculate_coordinate(c, d, e, f, g, h,…

一套可以替代人工的Cnc机床自动上下料机器人

Cnc机床自动上下料|整体解决方案 CNC机床自动上下料是指通过自动化设备和系统&#xff0c;实现CNC机床在加工过程中自动进行上下料操作。这种自动化系统通常包括自动送料机和卸料机&#xff0c;可以根据加工工件的尺寸和形状自动调整上下料的位置和角度&#xff0c;从而提高生产…

SpringCloud整合Zookeeper代替Eureka案例

文章目录 本期代码下载地址zookeeper简介zookeeper下载安装新建服务提供者测试 新建消费者测试 本期代码下载地址 地址:https://github.com/13thm/study_springcloud/tree/main/days4 zookeeper简介 zookeeper是一个分布式协调工具&#xff0c;可以实现注册中心功能 关闭Lin…

VMware Workstation Pro虚拟机搭建

下载链接&#xff1a;Download VMware Workstation Pro 点击上方下载&#xff0c;安装过程很简单&#xff0c;我再图片里面说明 等待安装中。。。。。是不是再考虑怎样激活&#xff0c;我都给你想好了&#xff0c;在下面这个链接&#xff0c;点赞收藏拿走不谢。 https://downl…

DBA技术栈MongoDB:简介

1.1 什么是MongoDB&#xff1f; MongoDB是一个可扩展、开源、表结构自由、用C语言编写且面向文档的数据库&#xff0c;旨在为Web应用程序提供高性能、高可用性且易扩展的数据存储解决方案。 MongoDB是一个介于关系数据库和非关系数据库之间的产品&#xff0c;是非关系数据库当…

ElasticSearch的常用增删改查DSL和代码

es增删改查常用语法 我们日常开发中&#xff0c;操作数据库写sql倒是不可能忘记&#xff0c;但是操作es的dsl语句有时候很容易忘记&#xff0c;特地记录一下方便查找。 DSL语句 1、创建索引 -- 创建索引 PUT /my_index {"mappings": {"properties": {&…

数据结构:链式栈

stack.h /* * 文件名称&#xff1a;stack.h * 创 建 者&#xff1a;cxy * 创建日期&#xff1a;2024年01月18日 * 描 述&#xff1a; */ #ifndef _STACK_H #define _STACK_H#include <stdio.h> #include <stdlib.h>typedef struct stack{int data…

查找局域网树莓派raspberry的mac地址和ip

依赖python库&#xff1a; pip install socket pip install scapy运行代码&#xff1a; import socket from scapy.layers.l2 import ARP, Ether, srpdef get_hostname(ip_address):try:return socket.gethostbyaddr(ip_address)[0]except socket.herror:# 未能解析主机名ret…