python自动化测试三部曲之request+django实现接口测试

这里废话少说,进入正题

我的思路是这样的

1、先用django实现登陆、增加、删除、查看4个接口

2、在excel定义好测试案例、然后读取excel中的案例,然后把案例用unittest框架组装和封装

3、启动django,执行测试案例

一、先跑通unittest到django的流程

1、先创建一个Django的项目

2、创建路由,这里我们使用二级路由

a、先复制工程目录下的urls.py文件到app目录下

b、修改工程目录下的urls.py文件,定义一级路由

c、修改app目录下的urls.py文件,设置二级路由,这里切记务必要删除默认的admin这条路由

d、定义这条路由指向的视图的函数

e、启动django,这里我们使用9090端口启动,因为我们的Jenkins端口用的是8080

E:\python\unittestForDjango>python manage.py runserver 9090

f、这里的是启动成功的样式,我圈住的告警可以忽略,因为这里Django的admin需要的,我们这里不会用到django的admin

g、打开浏览器访问django,我们的一个简单的Django项目已经跑通

3、在视图函数中定义一个方法,这个方法分别处理GET请求和POST请求

a、定义视图函数

这里通过这个参数告诉浏览器,我们返回的是JSON数据

1

return HttpResponse(result, content_type="application/json;charset=utf-8")

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

def test_login(request):

  method = request.method.upper()

  if method == "GET":

    result = {}

    name = request.GET.get("username",None)

    pwd = request.GET.get("pwd",None)

    result["name"] = name

    result["pwd"] = pwd

    result = json.dumps(result)

    # return HttpResponse(result)

    return HttpResponse(result, content_type="application/json;charset=utf-8")

  else:

    result = {}

    name = request.POST.get("username",None)

    pwd = request.POST.get("pwd",None)

    result["name"] = name

    result["pwd"] = pwd

    result = json.dumps(result)

    return HttpResponse(result,content_type="application/json;charset=utf-8")

b、使用request模块发起POST和GET请求

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

#Auther Bob

#--*--conding:utf-8 --*--

import requests

import json

class TestCase(object):

  def __init__(self,username,pwd,url):

    self.username = username

    self.pwd = pwd

    self.url = url

  def get(self):

    # 发送get请求

    url = self.url + "?username=" + str(self.username) + "&" + "pwd=" + str(self.pwd)

    res = requests.get(url=url)

    print(res.text,type(res.text))

  def post(self):

    # 发送post请求

    data = {

      "username" : self.username,

      "pwd" : self.pwd

    }

    res = requests.post(url=self.url,data=data)

    print(res.text)

if __name__ == '__main__':

  url = "http://127.0.0.1:9090/web/login/"

  username = "zhangsan"

  pwd = "123"

  t = TestCase(username,pwd,url)

  t.get()

  t.post()

c、这里我们引入unittest框架,测试案例可以这么写

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

import unittest

from test3 import test_request

class TestDjango(unittest.TestCase):

  

  def setUp(self):

    print("unittest框架的前置条件")

  def tearDown(self):

    print("unittest框架的后置条件")

  def test_01(self):

    url = "http://127.0.0.1:9090/web/login/"

    username = "zhangsan"

    pwd = "123"

    t = test_request.TestCase(url=url,username=username,pwd=pwd)

  def test_02(self):

    url = "http://127.0.0.1:9090/web/login/"

    username = "zhangsan"

    pwd = "123"

    t = test_request.TestCase(url=url,username=username,pwd=pwd)

    t.post()

if __name__ == '__main__':

  unittest.main(verbosity=2)

d、这里有重复代码,我们可以利用unittest框架中的classmethod来解决,因为实例化一个测试类可以放在前置条件中

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import unittest

from test3 import test_request

class TestDjango(unittest.TestCase):

  @classmethod

  def setUpClass(cls):

    url = "http://127.0.0.1:9090/web/login/"

    username = "zhangsan"

    pwd = "123"

    # 这里的t虽然是类变量,但是python的中的实例是可以用引用类变量的

    cls.t = test_request.TestCase(url=url,username=username,pwd=pwd)

  def setUp(self):

    print("unittest框架的前置条件")

  def tearDown(self):

    print("unittest框架的后置条件")

  def test_01(self):

    self.t.get()

  def test_02(self):

    self.t.post()

if __name__ == '__main__':

  unittest.main(verbosity=2)

e、在testcase中加入断言

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

import unittest

from test3 import test_request

class TestDjango(unittest.TestCase):

  @classmethod

  def setUpClass(cls):

    url = "http://127.0.0.1:9090/web/login/"

    username = "zhangsan"

    pwd = "123"

    # 这里的t虽然是类变量,但是python的中的实例是可以用引用类变量的

    cls.t = test_request.TestCase(url=url,username=username,pwd=pwd)

  def setUp(self):

    print("unittest框架的前置条件")

  def tearDown(self):

    print("unittest框架的后置条件")

  def test_01(self):

    res = self.t.get()

    self.assertEqual(200,res.status_code)

  def test_02(self):

    res = self.t.post()

    self.assertEqual(200, res.status_code)

if __name__ == '__main__':

  unittest.main(verbosity=2)

f、引入testsuite

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import unittest

from unittest import TestLoader

from test3 import test_unittest

if __name__ == '__main__':

  suite = unittest.TestSuite()

  loader = TestLoader()

  test_cases1 = unittest.TestLoader().loadTestsFromModule(test_unittest)

  # 参数是一个模块,会把这个模块里的所有case加载进来

  suite.addTests(test_cases1)

  runner = unittest.TextTestRunner(verbosity=2)

  runner.run(suite)

二、在django中设计接口

这里我们写一个简单的例子,设计一个用户表,设计4个接口

接口1:登陆

接口2:增加用户,需要用户登陆

接口3:删除用户,需要用户登陆

接口4:查询用户,不需要用户登陆

1、先看登陆接口

a、登录接口对应的url

下面是一级路由

1

url(r'^web/', include('unittesstApp1.urls'))

下面是二级路由

1

url(r'^login/', views.test_login),

b、登录接口的视图函数

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

def test_login(request):

  method = request.method.upper()

  if method == "GET":

    returndict = {"code": 200, "error": None}

    username = request.GET.get("username",None)

    password = request.GET.get("password",None)

    if username == "admin" and password == "admin123.":

      request.session["username"] = username

      request.session["password"] = password

      result = json.dumps(returndict)

    else:

      returndict["code"] = 201

      returndict["error"] = "用户名或者密码错误"

      result = json.dumps(returndict)

    return HttpResponse(result,content_type="application/json;charset=utf-8")

这里我们用到了session来代替cookies

2、增加用户接口

a、增加用户对应的url

一级路由同登陆接口,下面是二级路由

1

url(r'^add/', views.test_add),

b、增加用户接口对应的视图函数,这里我们做了各种异常处理,且判断了用户是否登陆,也就是通过是否携带cookies来判断

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

def test_add(request):

  method = request.method.upper()

  if method == "POST":

    returndict = {"code": 200, "error": None}

    username = request.session.get("username",None)

    password = request.session.get("password",None)

    if username == "admin" and password == "admin123.":

      newusername = request.POST.get("username",None)

      age = request.POST.get("age",None)

      sex = request.POST.get("sex",None)

      pwd = request.POST.get("pwd",None)

      userinfo = [newusername,age,sex,pwd]

      print(userinfo)

      if not "None" in userinfo and all(userinfo):

        if models.userInfo.objects.filter(username = userinfo[0]).exists():

          returndict["error"] = "{username} is exists,please add a new username".format(username = username)

          returndict["code"] = 201

          result = json.dumps(returndict)

          return HttpResponse(result, content_type="application/json;charset=utf-8")

        else:

          models.userInfo.objects.create(

            username = newusername,

            age = age,

            sex = sex,

            pwd = pwd

          )

          if models.userInfo.objects.filter(username=userinfo[0]).exists():

            result = json.dumps(returndict)

            return HttpResponse(result, content_type="application/json;charset=utf-8")

          else:

            returndict["error"] = "{username} is error,please retry add".format(username=username)

            returndict["code"] = 201

            result = json.dumps(returndict)

            return HttpResponse(result, content_type="application/json;charset=utf-8")

      else:

        returndict["error"] = "must input username,age,sex,pwd"

        returndict["code"] = 201

        result = json.dumps(returndict)

        return HttpResponse(result, content_type="application/json;charset=utf-8")

    else:

      returndict = {"code": 201, "error": "用户名或者密码错误"}

      result = json.dumps(returndict)

      return HttpResponse(result, content_type="application/json;charset=utf-8")

3、删除接口

a、删除用户对应的url

一级路由同登陆接口,这里只看二级路由

1

url(r'^del/', views.del_user),

b、删除接口对应的视图函数,这里我做了各种异常处理,也做了用户是否登陆的检测,也是通过检测cookies来实现

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

def del_user(request):

  method = request.method.upper()

  if method == "POST":

    returndict = {"code": 200, "error": None}

    username = request.session.get("username",None)

    password = request.session.get("password",None)

    if username == "admin" and password == "admin123.":

      delusername = request.POST.get("username",None)

      print(delusername)

      if delusername != None:

        if models.userInfo.objects.filter(username=delusername).exists():

          delid = models.userInfo.objects.get(username=delusername).id

          print(delid)

          try:

            models.userInfo.objects.get(id=delid).delete()

          except Exception as e:

            returndict = {"code": 201, "error": e}

            result = json.dumps(returndict)

            return HttpResponse(result, content_type="application/json;charset=utf-8")

          else:

            result = json.dumps(returndict)

            return HttpResponse(result, content_type="application/json;charset=utf-8")

        else:

          returndict = {"code": 201, "error": "{username} is not exists".format(username = delusername)}

          result = json.dumps(returndict)

          return HttpResponse(result, content_type="application/json;charset=utf-8")

      else:

        returndict = {"code": 201, "error": "you must input a username"}

        result = json.dumps(returndict)

        return HttpResponse(result, content_type="application/json;charset=utf-8")

    else:

      returndict = {"code": 201, "error": "username or password is error"}

      result = json.dumps(returndict)

      return HttpResponse(result, content_type="application/json;charset=utf-8")

4、查看接口

a、查看接口对应的url

一级路由同登陆接口url,下面是二级路由

1

url(r'^scan/', views.get_user),

b、查看接口对应的url,这里我们不检测用户是否登陆,直接把查到的数据返回给客户,如果查询报错,才返回错误的信息

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

def get_user(request):

  method = request.method.upper()

  returndict = {"code": 200, "userinfo": None}

  if method == "GET":

    try:

      alluser = models.userInfo.objects.all().values_list("username")

      alluserlist = []

      for i in alluser:

        alluserlist.append(i)

         

      returndict["userinfo"] = alluserlist

    except Exception as e:

      returndict["code"] = "201"

      returndict["error"] = e

    finally:

      result = json.dumps(returndict)

      return HttpResponse(result, content_type="application/json;charset=utf-8")

5、设计删除数据库中所有的接口,用来做后置条件

1

2

3

4

5

6

7

8

9

10

11

def del_alluser(request):

  method = request.method.upper()

  if method == "POST":

    returndict = {"code": 200, "error": None}

    username = request.session.get("username", None)

    password = request.session.get("password", None)

    if username == "admin" and password == "admin123.":

      if models.userInfo.objects.all().count() > 0:

        models.userInfo.objects.all().delete()

      result = json.dumps(returndict)

      return HttpResponse(result, content_type="application/json;charset=utf-8")

三、案例准备

1、在excel中写好接口测试案例

2、定义常量,也就是每列对应的值

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

class TestConfig(object):

  def __init__(self):

    self.name = 0

    self.url = 1

    self.method = 2

    self.cookies = 3

    self.data = 4

    self.res = 5

    self.exec = 6

  def getname(self):

    return self.name

  def geturl(self):

    return self.url

  def getmethod(self):

    return self.method

  def getcookies(self):

    return self.cookies

  def getdata(self):

    return self.data

  def getres(self):

    return self.res

  def getexec(self):

    return self.exec

3、定义读取excel的类,因为我要从excel中读取案例

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

import xlrd

import os

class testexcel(object):

  casepath = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "case", "testcase.xlsx")

  def __init__(self):

    self.casepath = testexcel.casepath

    self.execlobj = xlrd.open_workbook(self.casepath)

    self.sheetobj = self.execlobj.sheet_by_index(0)

  def get_excel_data(self,row,col):

    max_row = self.get_excel_max_row()

    max_col = self.get_excel_max_col()

    if row > max_row -1 or col > max_col - 1:

      return False

    else:

      data = self.sheetobj.cell_value(row,col)

      return data

  def get_excel_max_row(self):

    r_num = self.sheetobj.nrows

    return r_num

  def get_excel_max_col(self):

    c_num = self.sheetobj.ncols

    return c_num

4、定义我们的接口函数

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

import requests

import json

class TestLogin(object):

  def __init__(self,username,pwd,url):

    self.username = username

    self.pwd = pwd

    self.url = url

  def get(self):

    # 发送get请求

    url = self.url + "?username=" + str(self.username) + "&" + "password=" + str(self.pwd)

    res = requests.get(url=url,

              headers={

           "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"

         })

    # print(json.loads(res.text))

    return res

  def post(self):

    # 发送post请求

    data = {

      "username" : self.username,

      "pwd" : self.pwd

    }

    res = requests.post(url=self.url,

              data=data,

              headers={

                "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"

              },

              )

    # print(res.text)

    return res

class TestAdd(object):

  def __init__(self,username,age,sex,pwd,cookies,url):

    self.username = username

    self.age = age

    self.sex = sex

    self.pwd = pwd

    self.url = url

    self.cookies = cookies

  def post(self):

    # 发送post请求

    data = {

      "username" : self.username,

      "pwd" : self.pwd,

      "age" : self.age,

      "sex" : self.sex

    }

    res = requests.post(url=self.url,

              data=data,

              headers={

                "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"

              },

              cookies=self.cookies,

              )

    # print(res.text)

    return res

class Testdel(object):

  def __init__(self, username,cookies,url):

    self.username = username

    self.cookies = cookies

    self.url = url

  def post(self):

    # 发送post请求

    data = {

      "username": self.username,

    }

    res = requests.post(url=self.url,

              data=data,

              headers={

                "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"

              },

              cookies=self.cookies,

              )

    # print(res.text)

    return res

class Testscan(object):

  def __init__(self,url):

    self.url = url

  def get(self):

    res = requests.get(url=self.url,

              headers={

                "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"

              },

              cookies=None,

              )

    return res

5、定义测试案例

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

import unittest

from test3 import test_request

import json

from util import test_json

from util import test_excel

from case import testconfig

import requests

class TestDjango(unittest.TestCase):

  @classmethod

  def setUpClass(cls):

    cls.alldata = test_json.testjson()

  @classmethod

  def tearDownClass(cls):

    url = "http://127.0.0.1:9090/web/login/" + "?username=" + "admin" + "&" + "password=" + "admin123."

    res = requests.get(url=url,

              headers={

           "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"

         })

    url = "http://127.0.0.1:9090/web/delall/"

    requests.post(url=url,

           headers={

             "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"

           },

           cookies = res.cookies

           )

  def get_cookies(self):

    url = "http://127.0.0.1:9090/web/login/" + "?username=" + "admin" + "&" + "password=" + "admin123."

    res = requests.get(url=url,

              headers={

           "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"

         })

    # print(json.loads(res.text))

    return res.cookies

  @unittest.skip('noexec')

  def test_login_ok(self):

    row = 1

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row,configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      data = json.loads(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "GET":

        testobj = test_request.TestLogin(data["username"],data["pwd"],url)

        resobj = testobj.get()

        self.assertEqual(int(res),json.loads(resobj.text)["code"])

  @unittest.skip('noexec')

  def test_login_pwd_error(self):

    row = 2

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row,configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      data = json.loads(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "GET":

        testobj = test_request.TestLogin(data["username"],data["pwd"],url)

        resobj = testobj.get()

        self.assertEqual(int(res),json.loads(resobj.text)["code"])

  @unittest.skip('noexec')

  def test_login_user_error(self):

    row = 3

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row,configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      data = json.loads(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "GET":

        testobj = test_request.TestLogin(data["username"],data["pwd"],url)

        resobj = testobj.get()

        self.assertEqual(int(res),json.loads(resobj.text)["code"])

  @unittest.skip('noexec')

  def test_user_pwd_error(self):

    row = 4

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row,configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      data = json.loads(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "GET":

        testobj = test_request.TestLogin(data["username"],data["pwd"],url)

        resobj = testobj.get()

        self.assertEqual(int(res),json.loads(resobj.text)["code"])

  @unittest.skip('noexec')

  def test_insert_ok(self):

    row = 5

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row, configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      data = json.loads(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "POST":

        testobj = test_request.TestAdd(data["username"], data["age"],data["sex"], data["pwd"],cookies,url)

        resobj = testobj.post()

        print(json.loads(resobj.text))

        self.assertEqual(int(res), json.loads(resobj.text)["code"])

  @unittest.skip('noexec')

  def test_insert_nologin(self):

    row = 6

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row, configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      data = json.loads(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "POST":

        testobj = test_request.TestAdd(data["username"], data["age"],data["sex"], data["pwd"],cookies,url)

        resobj = testobj.post()

        print(json.loads(resobj.text))

        self.assertEqual(int(res), json.loads(resobj.text)["code"])

  @unittest.skip("noexec")

  def test_insert_user_error(self):

    row = 7

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row, configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      data = json.loads(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "POST":

        testobj = test_request.TestAdd(data.get("username",None), data.get("age",None), data.get("sex",None), data.get("pwd",None), cookies, url)

        resobj = testobj.post()

        print(json.loads(resobj.text))

        self.assertEqual(int(res), json.loads(resobj.text)["code"])

  @unittest.skip('no exec')

  def test_insert_pwd_error(self):

    row = 8

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row, configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      data = json.loads(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "POST":

        testobj = test_request.TestAdd(data.get("username",None), data.get("age",None), data.get("sex",None), data.get("pwd",None), cookies, url)

        resobj = testobj.post()

        print(json.loads(resobj.text))

        self.assertEqual(int(res), json.loads(resobj.text)["code"])

  @unittest.skip("no exec")

  def test_insert_sex_error(self):

    row = 9

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row, configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      print(data)

      data = json.loads(data)

      print(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "POST":

        testobj = test_request.TestAdd(data.get("username",None), data.get("age",None), data.get("sex",None), data.get("pwd",None), cookies, url)

        resobj = testobj.post()

        print(json.loads(resobj.text))

        self.assertEqual(int(res), json.loads(resobj.text)["code"])

  @unittest.skip('no exec')

  def test_insert_age_error(self):

    row = 10

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row, configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      print(data)

      data = json.loads(data)

      print(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "POST":

        testobj = test_request.TestAdd(data.get("username",None), data.get("age",None), data.get("sex",None), data.get("pwd",None), cookies, url)

        resobj = testobj.post()

        print(resobj.text)

        print(json.loads(resobj.text))

        self.assertEqual(int(res), json.loads(resobj.text)["code"])

  @unittest.skip('no exec')

  def test_insert_user_exist(self):

    row = 11

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row, configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      print(data)

      data = json.loads(data)

      print(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "POST":

        testobj = test_request.TestAdd(data.get("username", None), data.get("age", None), data.get("sex", None),

                        data.get("pwd", None), cookies, url)

        resobj = testobj.post()

        print(resobj.text)

        print(json.loads(resobj.text))

        self.assertEqual(int(res), json.loads(resobj.text)["code"])

  def test_get_user(self):

    row = 12

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row, configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "POST":

        testobj = test_request.Testscan(url)

        resobj = testobj.get()

        # print(resobj.text

        print(json.loads(resobj.text))

        self.assertEqual(int(res), json.loads(resobj.text)["code"])

  @unittest.skip('no exec')

  def test_del_user(self):

    row = 13

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row, configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      print(data)

      data = json.loads(data)

      print(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "POST":

        testobj = test_request.Testdel(data.get("username", None),cookies, url)

        resobj = testobj.post()

        print(resobj.text)

        print(json.loads(resobj.text))

        self.assertEqual(int(res), json.loads(resobj.text)["code"])

  def test_del_noexistuser(self):

    row = 14

    configobj = testconfig.TestConfig()

    excelobj = test_excel.testexcel()

    execstatus = excelobj.get_excel_data(row, configobj.getexec())

    if execstatus == "YES":

      cookiesstatus = excelobj.get_excel_data(row, configobj.getcookies())

      if cookiesstatus == "YES":

        cookies = self.get_cookies()

      else:

        cookies = None

      data = excelobj.get_excel_data(row, configobj.getdata())

      print(data)

      data = json.loads(data)

      print(data)

      url = excelobj.get_excel_data(row, configobj.geturl())

      res = excelobj.get_excel_data(row, configobj.getres())

      method = excelobj.get_excel_data(row, configobj.getmethod())

      if method == "POST":

        testobj = test_request.Testdel(data.get("username", None),cookies, url)

        resobj = testobj.post()

        print(resobj.text)

        print(json.loads(resobj.text))

        self.assertEqual(int(res), json.loads(resobj.text)["code"])

6、引入unittest的suit,组织案例

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import unittest

from unittest import TestLoader

from test3 import test_unittest

if __name__ == '__main__':

  suite = unittest.TestSuite()

  loader = TestLoader()

  test_cases1 = unittest.TestLoader().loadTestsFromModule(test_unittest)

  # 参数是一个模块,会把这个模块里的所有case加载进来

  suite.addTests(test_cases1)

  runner = unittest.TextTestRunner(verbosity=2)

  runner.run(suite)

四、执行案例

1、启动django

E:\python\unittestForDjango>python manage.py runserver 9090
Performing system checks...

System check identified no issues (0 silenced).
October 19, 2019 - 22:46:42
Django version 1.11.7, using settings 'unittestForDjango.settings'
Starting development server at http://127.0.0.1:9090/
Quit the server with CTRL-BREAK

2、执行测试套件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

test_del_noexistuser (test3.test_unittest.TestDjango) ... {"username":"test1"}

{'username': 'test1'}

ok

test_del_user (test3.test_unittest.TestDjango) ... skipped 'no exec'

test_get_user (test3.test_unittest.TestDjango) ... {"code": 201, "error": "test1 is not exists"}

{'code': 201, 'error': 'test1 is not exists'}

{'code': 200, 'userinfo': []}

ok

test_insert_age_error (test3.test_unittest.TestDjango) ... skipped 'no exec'

test_insert_nologin (test3.test_unittest.TestDjango) ... skipped 'noexec'

test_insert_ok (test3.test_unittest.TestDjango) ... skipped 'noexec'

test_insert_pwd_error (test3.test_unittest.TestDjango) ... skipped 'no exec'

test_insert_sex_error (test3.test_unittest.TestDjango) ... skipped 'no exec'

test_insert_user_error (test3.test_unittest.TestDjango) ... skipped 'noexec'

test_insert_user_exist (test3.test_unittest.TestDjango) ... skipped 'no exec'

test_login_ok (test3.test_unittest.TestDjango) ... skipped 'noexec'

test_login_pwd_error (test3.test_unittest.TestDjango) ... skipped 'noexec'

test_login_user_error (test3.test_unittest.TestDjango) ... skipped 'noexec'

test_user_pwd_error (test3.test_unittest.TestDjango) ... skipped 'noexec'

----------------------------------------------------------------------

Ran 14 tests in 1.466s

OK (skipped=12)

​现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:485187702【暗号:csdn11】

最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 希望能帮助到你!【100%无套路免费领取】

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Scikit-Learn逻辑回归

Scikit-Learn逻辑回归 1、逻辑回归概述1.1、逻辑回归1.2、逻辑回归的优缺点1.3、逻辑回归与线性回归 2、逻辑回归的原理2.1、逻辑回归的概念与原理2.2、逻辑回归的损失函数 3、 1、逻辑回归概述 1.1、逻辑回归 逻辑回归(Logistic Regression)主要解决二…

【IDEA】java 项目启动偶现Kotlin 版本问题 error:Kotlin:module was

一、问题描述: error:Kotlin:module was compiled with an incompatible version of kotlin the binary version of its metadata is二、问题原因: jar包版本冲突 三、解决方式: 1、Rebuild Project(推荐☆) 重新构…

【web】云导航项目部署及环境搭建(复杂)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言一、项目介绍1.1项目环境架构LNMP1.2项目代码说明 二、项目环境搭建2.1 Nginx安装2.2 php安装2.3 nginx配置和php配置2.3.1 修改nginx文件2.3.2 修改vim /etc/p…

内存溢出排查

1、进入k8s容器对应服务节点查看进程号 ps aux|grep javaps aux 是用BSD的格式来显示 java这个进程 显示的项目有:USER , PID , %CPU , %MEM , VSZ , RSS , TTY , STAT , START , TIME , COMMAND USER: 行程拥有者 PID: pid %CPU: 占用的 CPU 使用率 %MEM: 占用的记…

python Airtest自动化测试工具的的使用

Airtest全称AirtestProject,是由网易游戏推出的一款自动化测试框架,在软件测试的时候使用到了该框架。这里记录一下安装、使用和遇到的坑的问题… Airtest的官网介绍项目构成 Airtest:是一个跨平台的、基于图像识别的UI自动化测试框架&#x…

YOLOv9尝鲜测试五分钟极简配置

pip安装python包: pip install yolov9pip在https://github.com/WongKinYiu/yolov9/tree/main中下载好权重文件yolov9-c.pt。 运行下面代码: import yolov9model yolov9.load("yolov9-c.pt", device"cpu") # load pretrained or c…

观察者模式与发布订阅模式

观察者模式 定义: 观察者模式是一种行为型设计模式,定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。 结构图: ES6简易代码实现: //ts环境下…

Uncertainty-Aware Mean Teacher(UA-MT)

Uncertainty-Aware Mean Teacher 0 FQA:1 UA-MT1.1 Introduction:1.2 semi-supervised segmentation1.3 Uncertainty-Aware Mean Teacher Framework 参考: 0 FQA: Q1: 不确定感知是什么意思?不确定信息是啥?Q2:这篇文章的精妙的点…

300分钟吃透分布式缓存-14讲:大数据时代,MC如何应对新的常见问题?

大数据时代 Memcached 经典问题 随着互联网的快速发展和普及,人类进入了大数据时代。在大数据时代,移动设备全面融入了人们的工作和生活,各种数据以前所未有的 速度被生产、挖掘和消费。移动互联网系统也不断演进和发展,存储、计…

掌握“这招”,平趴也能轻松捕获威胁情报!——利用流行度排名升级威胁情报收集

引言 威胁情报是提供强大网络安全服务的重要基石,这些服务可以保护各地的移动设备和互联网用户。但当今的互联网威胁是复杂且具有强适应性的,它们通过不断改变其面貌以逃避安全防御。这使得提供涵盖各种威胁形势的威胁情报变得日益困难,组织…

工具篇-- 定时任务xxl-job

文章目录 前言一、xxl-job 运行:1.1 下载并且启动:1.2 项目介绍:1.2.1 xxl-job-admin:1.2.1.1 xxl-job-admin 作用:1.2.1.2 xxl-job-admin 的配置: 1.2.2 xxl-job-executor-samples:1.2.2.1 pom…

51.仿简道云公式函数实战-文本函数-JOIN

1. JOIN函数 JOIN 函数可通过连接符将数组的值连成文本。 2. 函数用法 JOIN(数组,"连接符") 3. 函数示例 如需将复选框中勾选的选项通过”-“组合在一起,则可设置公式为JOIN(复选框组,"-") 4. 代码实战 首先我们在function包下创建text包…

基于springboot的新闻资讯系统的设计与实现

**🍅点赞收藏关注 → 私信领取本源代码、数据库🍅 本人在Java毕业设计领域有多年的经验,陆续会更新更多优质的Java实战项目希望你能有所收获,少走一些弯路。🍅关注我不迷路🍅**一 、设计说明 1.1 课题背景…

Qt QWidget 简约美观的加载动画 第四季

&#x1f60a; 第四季来啦 &#x1f60a; 效果如下: 只有三个文件,可以直接编译运行的 //main.cpp #include "LoadingAnimWidget.h" #include <QApplication> #include <QVBoxLayout> #include <QGridLayout> int main(int argc, char *argv[]) …

亚洲唯一!京东荣获2024年度Gartner供应链技术创新奖背后的创新探索

序言&#xff1a; 序言&#xff1a;2月14日晚间&#xff0c;Gartner公布了2024年度Garter Power of the Profession供应链大奖&#xff0c;京东集团荣获供应链技术创新奖&#xff0c;成为获得该奖项的唯一亚洲企业。Gartner Power of the Profession供应链奖项已经举办十年&am…

驻场人员严重划水,愈演愈烈,要请领导出面吗?

你有没有遇到过团队成员偷懒的情况&#xff1f;比如你们一起完成某个项目目标&#xff0c;干着干着你发现&#xff0c;就只有你和几个核心人员比较上心&#xff0c;很多人都在划水。 你可能会觉得这是因为大家工作态度不好&#xff0c;甚至怀疑他们的人品&#xff0c;忍不住想…

MoonBit支持云原生调试功能

MoonBit 更新 1. 支持云原生调试功能 现在&#xff0c;你可以通过访问try.moonbitlang.cn&#xff0c;直接在浏览器中使用 devtools 调试 MoonBit 程序&#xff0c;无需安装任何软件。具体的使用步骤如下&#xff1a; 2. MoonBit 支持使用 for 关键字定义的函数式循环控制流 …

ShardingJDBC分库分表

目录 ShardingSphere ShardingJDBC客户端分库分表 ShardingProxy服务端分库分表 两者对比 ShardingJDBC分库分表实战 需求 步骤 分片策略汇总 ShardingSphere ShardingSphere最为核心的产品有两个&#xff1a;一个是ShardingJDBC&#xff0c;这是一个进行客户端分库分表…

Linux命令行常用命令

初识shell shell是系统的用户界面&#xff0c;提供了用户与内核进行交互操作的一种接口。它接收用户输入的命令并把它送入内核去执行。实际上shell是一个命令解释器&#xff0c;它解释用户输入的命令并且把用户的意图传达给内核。&#xff08;可以理解为用户与内核之间的翻译官…

npm/nodejs安装、切换源

前言 发现自己电脑上没有npm也没有node很震惊&#xff0c;难道我没写过代码么&#xff1f;不扯了&#xff0c;进入正题哈哈…… 安装 一般没有npm的话会报错&#xff1a; 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称而且报这个错&#xff0c;我们执行…
最新文章