2
schangxiang@126.com
2024-10-02 5d523171b8bc7db46ca76b11640dbfcb0120ce84
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
 
using iWareCommon.Utils;
using iWareModel;
using iWareTestForm.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
 
 
 
 
namespace iWareTestForm
{
    public partial class InterFaceTestForm : Form
    {
        AutoSizeFormClass asc = new AutoSizeFormClass();
 
        delegate string GetSelectInterFaceCallBack();
        delegate void Delegate_SetPostResult(int count, string content);
        delegate void Delegate_SetPost(int count, string param);
 
        string wipHost = BLLHelpler.GetConfigValue("wipHost");
        /// <summary>
        /// 频率
        /// </summary>
        private int callHZ = 1;
        /// <summary>
        /// 请求次数
        /// </summary>
        private int requestCount = 0;
        /// <summary>
        /// 默认请求次数
        /// </summary>
        private int default_requestCount = 200;
        private string curSelUrl = "";
 
        private long totalUseTime = 0;//全部请求的时间和
 
        public InterFaceTestForm()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
 
            Init();
        }
        private void Init()
        {
            List<ListItem> itemList = GetItems();
            foreach (var item in itemList)
            {
                comBox_InterFaces.Items.Add(item);
            }
            comBox_InterFaces.SelectedIndex = 0;
            this.tb_CallHZ.Text = "1000";
            callHZ = 1;
            this.tb_RequestCount.Text = default_requestCount.ToString();
            requestCount = default_requestCount;
            this.tb_timestamp.Text = SimulatorCommonHelper.GetTimeStampWithlocals();
        }
 
        private void btn_Test_Click(object sender, EventArgs e)
        {
            InitData();
            Post(1);
        }
 
        private void Post(int count)
        {
            string param = this.tb_Params.Text.Trim();
            #region POST请求
 
            try
            {
                string url = GetSelectInterFace();
                string result = RealPost(wipHost, url, param, count);
                ShowResult(count, string.Format("第{0}次请求返回结果{1}", count.ToString(), result));
            }
            catch (Exception ex)
            {
                MessageBox.Show("出现异常:" + ex.Message);
                return;
            }
 
            #endregion
        }
 
 
        /// <summary>
        /// 性能测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_performanceTest_Click(object sender, EventArgs e)
        {
 
            InitData();
            string param = this.tb_Params.Text.Trim();
            //*/
            try
            {
                totalUseTime = 0;
                callHZ = Convert.ToInt32(this.tb_CallHZ.Text.Trim());
                requestCount = Convert.ToInt32(this.tb_RequestCount.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show("出现异常:" + ex.Message);
                return;
            }
 
            if (!this.cb_timestamp.Checked)
            {//时间戳不突变
                if (this.tb_timestamp.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("时间戳不突变的情况下,时间戳不能为空!");
                    this.tb_timestamp.Focus();
                    return;
                }
            }
 
            ParameterizedThreadStart paramStart = new ParameterizedThreadStart(PerformanceTest);
            Thread thread = new Thread(paramStart);
            Object obj = param;
            thread.Start(obj);
        }
        private void PerformanceTest(object param)
        {
 
            string url = GetSelectInterFace();
            DateTime bgtime = DateTime.Now;
            var timestamp = "";
            string start_timestamp = "", end_timestamp = "";//开始和结束时间戳
            for (int i = 1; i < requestCount + 1; i++)
            {
                if (i != 1)
                    Thread.Sleep(callHZ);
                var str_param = param.ToString();
                if (this.ckb_ParamChange.Checked)
                {//参数突变
                    str_param = str_param.Replace("$MutationParam$", Guid.NewGuid().ToString().Substring(0, 5));
                }
 
                if (this.cb_timestamp.Checked)
                {//时间戳突变
                    timestamp = SimulatorCommonHelper.GetTimeStampWithlocals();
                }
                else
                {//时间戳不突变
                    timestamp = this.tb_timestamp.Text.Trim();
                }
                str_param = str_param.Replace("$timestamp$", timestamp);
 
                if (i == 1)
                {
                    start_timestamp = timestamp;
                }
                else if (i == requestCount)
                {
                    end_timestamp = timestamp;
                }
 
                MyMethod(bgtime, start_timestamp, end_timestamp, i, str_param, url);
                //SetPostResult22(i, "异步方法" + i.ToString() + "调用完成");
            }
        }
 
 
 
        /// <summary>
        /// 获取接口下拉
        /// </summary>
        /// <returns></returns>
        private string GetSelectInterFace()
        {
            //多线程调用时要查检控件的InvokeRequired,若未在其他线程中访问,可直接赋值。若在调用,要用Invoke来调用代理完成。
            if (this.comBox_InterFaces.InvokeRequired)
            {
                GetSelectInterFaceCallBack callBack = new GetSelectInterFaceCallBack(GetSelectInterFace);
                return this.Invoke(callBack).ToString();
            }
            else
            {
                return (this.comBox_InterFaces.SelectedItem as ListItem).Value;
            }
        }
 
 
        /// <summary>
        /// 显示请求结果
        /// </summary>
        /// <param name="count"></param>
        /// <param name="content"></param>
        private void ShowResult(int count, string content)
        {
 
            if (this.tb_PostResult.InvokeRequired)
            {
                Delegate_SetPostResult delegate_SetPostResult = new Delegate_SetPostResult(ShowResult);
                this.Invoke(delegate_SetPostResult, new object[] { count, content });
            }
            else
            {
                content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  " + content + " \r\n";
                this.tb_ResponseResult.Text = this.tb_ResponseResult.Text + content;
            }
        }
 
        /// <summary>
        /// 显示请求信息
        /// </summary>
        /// <param name="count"></param>
        /// <param name="param"></param>
        private void ShowPostInfo(int count, string param)
        {
 
            if (this.tb_PostResult.InvokeRequired)
            {
                Delegate_SetPost delegate_SetPostResult = new Delegate_SetPost(ShowPostInfo);
                this.Invoke(delegate_SetPostResult, new object[] { count, param });
            }
            else
            {
                string content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  第" + count.ToString() + "次请求... \r\n";
                content += "参数:" + param + "\r\n";
                this.tb_PostResult.Text = this.tb_PostResult.Text + content;
            }
        }
 
        #region 异步方法
 
        private async Task<string> MyMethod(DateTime bgtime, string start_timestamp, string end_timestamp, int i, string param, string url)
        {
            string r = await Task.Run(() =>
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
                //var startTime = WIPCommon.ForamtCurDateTimeWithF();
                string result = RealPost(wipHost, url, param, i);
                //var endTime = WIPCommon.ForamtCurDateTimeWithF();
                stopWatch.Stop();
                ShowResult(i, string.Format("第{0}次请求返回结果{1}", i.ToString(), result));
                ShowResult(i, string.Format("第{0}次请求结束,用时:" + stopWatch.ElapsedMilliseconds.ToString() + "(毫秒)", i.ToString()));
                totalUseTime += stopWatch.ElapsedMilliseconds;
                return result;
                //return (i * 2).ToString();
            });
            //ShowResult(i, string.Format("异步方法{0}执行完毕,结果{1}", i.ToString(), r));
            if (i == requestCount)
            {
                ShowResult(i,
                    "请求结束,总用时:" + (DateTime.Now - bgtime).TotalMilliseconds.ToString()
                    + "(毫秒),平均用时:" + (totalUseTime / requestCount).ToString("0") + "(毫秒)"
                    + ",【开始时间戳:" + start_timestamp + ",结束时间戳:" + end_timestamp + "】"
                    + ",【查询开始时间戳:" + (Convert.ToInt64(start_timestamp) - 1).ToString() + "000,查询结束时间戳:" + (Convert.ToInt64(end_timestamp) + 1).ToString() + "000】");
            }
            return r;
        }
 
        #endregion
 
 
        private string RealPost(string host, string url, string param, int count)
        {
            return "";
            /*
            string result = "";
            try
            {
                ShowPostInfo(count, param);
                //result = new HTTPService(host).postContentForString(url, param, new Guid());
                result = new HTTPLongConnectionService2().postContentForString(url, param);
            }
            catch (Exception ex)
            {
                result = string.Format("请求出现异常,ex:{0},参数->host:{1},url:{2},param:{3},count:{4}",
                     JsonConvert.SerializeObject(ex), host, url, param, count.ToString());
            }
            return result;
            //*/
        }
 
        private void btn_Stop_Click(object sender, EventArgs e)
        {
            requestCount = 0;
            this.btn_performanceTest.Enabled = true;
            this.btn_Test.Enabled = true;
        }
 
 
        #region 公共方法
 
        /// <summary>
        /// 获取完整地址
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private string GetURL(string url)
        {
            return wipHost + url;
        }
 
        private List<ListItem> GetItems()
        {
            List<ListItem> list = new List<ListItem>();
            InterfaceSection services = InterfaceSection.GetConfig();
            foreach (TheKeyValue item in services.KeyValues)
            {
                list.Add(new ListItem()
                {
                    Text = item.Name,
                    Value = item.Url
                });
            }
            return list;
        }
 
        private void InitData()
        {
            this.tb_PostResult.Text = "";
            this.tb_ResponseResult.Text = "";
            //this.btn_performanceTest.Enabled = false;
            //this.btn_Test.Enabled = false;
 
            if (this.comBox_InterFaces.SelectedIndex == -1)
            {
                MessageBox.Show("请选择接口!");
                return;
            }
            curSelUrl = GetSelectInterFace();
            this.lbl_URL.Text = GetURL(curSelUrl);
        }
 
        #endregion
 
        private void comBox_InterFaces_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                curSelUrl = GetSelectInterFace();
                this.lbl_URL.Text = GetURL(curSelUrl);
                var selItem = (ListItem)this.comBox_InterFaces.SelectedItem;
                if (selItem != null)
                {
                    string json = JsonFileHelper.ReadJson(@"Templete\" + selItem.Text + ".json");
                    //json = json.Replace("$timestamp$", CommonHelper.GetTimeStampWithlocals());
                    json = json.Replace("$testValue$", "test");
                    this.tb_Params.Text = json;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("出现错误:" + ex.Message);
            }
 
        }
 
        private void InterFaceTestForm_Load(object sender, EventArgs e)
        {
            asc.controllInitializeSize(this);
        }
 
        private void tb_PostResult_TextChanged(object sender, EventArgs e)
        {
            tb_PostResult.SelectionStart = tb_PostResult.Text.Length;
            tb_PostResult.ScrollToCaret();
        }
 
        private void tb_ResponseResult_TextChanged(object sender, EventArgs e)
        {
            tb_ResponseResult.SelectionStart = tb_ResponseResult.Text.Length;
            tb_ResponseResult.ScrollToCaret();
        }
 
        private void InterFaceTestForm_SizeChanged(object sender, EventArgs e)
        {
            asc.controlAutoSize(this);
        }
 
        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
 
        private void btn_NewTimeStamp_Click(object sender, EventArgs e)
        {
            this.tb_timestamp.Text = SimulatorCommonHelper.GetTimeStampWithlocals();
        }
    }
}