-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlocustfile.py
256 lines (232 loc) · 9.48 KB
/
locustfile.py
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
import os
import sys
import random
import csv
import logging
from lxml import etree
from locust import HttpLocust, TaskSet, task
logger = logging.getLogger(__name__)
IMG_DIR = os.path.join(os.path.dirname(__file__), 'locust_images')
SITE_ID = 'test-site'
USER = 'admin'
PASS = 'aLv7Eb6ju9aV7O'
ALL_IMAGES = []
VIEW_URLS = ('', '/view', '/@@images/image/thumb', '/@@images/image/mini',
'/@@images/image/preview', '/@@images/image/large',
'/@@images/image/icon')
def select_image():
files = os.listdir(IMG_DIR)
fname = random.choice(files)
path = os.path.join(IMG_DIR, fname)
return fname, open(path, 'r')
class ImageCreator(TaskSet):
created_images = []
def login(self):
with self.client.post("/" + SITE_ID + "/login_form", {
"__ac_name": USER,
"__ac_password": PASS,
"came_from": "",
"next": "",
"target": "",
"form.submitted": "1",
"js_enabled": "0",
"cookies_enabled": "1",
"login_name": USER,
"pwd_empty": "0",
"submit": "Log in"},
catch_response=True) as resp:
if 'You are now logged in' not in resp.content:
resp.failure('Could not login')
def logout(self):
self.client.get('/' + SITE_ID + '/logout')
def _add_image(self, img_id, title, img_file):
with self.client.post(
"/" + SITE_ID +
"/portal_factory/Image/image.{}/atct_edit".format(
title
), data={
'id': img_id,
'title': title,
'description': 'Some Description',
'description_text_format': 'text/plain',
'form.button.save': 'Save',
'form.submitted': '1',
'last_referer': '/' + SITE_ID + '/'
}, files={'image_file': img_file},
catch_response=True) as resp:
if resp.status_code != 200:
resp.raise_for_status()
if 'Changes saved.' not in resp.content:
html = etree.HTML(resp.content)
errors = html.xpath('//div[@class="fieldErrorBox"]/text()')
errors = '; '.join(e for e in errors if e)
resp.failure(errors)
return
return resp.url.split('/')[-2]
@task
def add_image(self):
self.login()
number = random.randint(1, sys.maxint)
fname, img_file = select_image()
img_id = '{}-{}.jpg'.format(fname, number)
title = fname
with img_file as img:
new_id = self._add_image(img_id, title, img)
if new_id:
ALL_IMAGES.append(new_id)
self.logout()
self.interrupt(True)
class SiteBrowser(TaskSet):
tasks = {ImageCreator: 1}
login = ImageCreator.login.im_func
logout = ImageCreator.logout.im_func
@task(15)
def view_image(self):
if ALL_IMAGES:
img_id = random.choice(ALL_IMAGES)
more = random.choice(VIEW_URLS)
self.client.get('/' + SITE_ID + '/images/' + img_id + more)
else:
self.client.get("/" + SITE_ID + '/')
@task(2)
def index(self):
self.client.get("/" + SITE_ID + '/images')
@task(1)
def site_root(self):
self.client.get("/" + SITE_ID + '/')
def create_site(self):
has_site = False
with self.client.get('/' + SITE_ID + '/', catch_response=True) as resp:
if resp.status_code == 200:
has_site = True
if not has_site:
self.client.auth = (USER, PASS)
with self.client.post('/@@plone-addsite', data={
'site_id': SITE_ID,
'title': 'Test Site',
'default_language': 'en',
'setup_content:boolean': 'true',
'form.submitted:boolean': 'True',
'extension_ids:list': 'plonetheme.classic:default',
'extension_ids:list': 'plonetheme.sunburst:default',
'submit': 'Create Plone Site'}, catch_response=True) as resp:
if resp.status_code != 200:
resp.raise_for_status()
if 'Welcome to Plone' not in resp.content:
resp.failure('Site not created')
self.client.auth = False
return
with self.client.get('/' + SITE_ID + '/images',
catch_response=True) as resp:
if resp.status_code == 200:
return
# Create an image folder
with self.client.post(
"/" + SITE_ID +
"/portal_factory/Folder/folder.{}/atct_edit".format(
'images'
), data={
'id': 'images',
'title': 'Images',
'description': 'Image Folder',
'description_text_format': 'text/plain',
'form.button.save': 'Save',
'form.submitted': '1',
'last_referer': '/' + SITE_ID + '/'
}, catch_response=True) as resp:
if resp.status_code >= 400:
self.client.auth = False
resp.raise_for_status()
if 'Changes saved.' not in resp.content:
html = etree.HTML(resp.content)
errors = html.xpath('//div[@class="fieldErrorBox"]/text()')
errors = '; '.join(e for e in errors if e)
self.client.auth = False
resp.failure(errors)
return
# Publish the Folder
with self.client.get(
"/" + SITE_ID +
"/images/content_status_modify?workflow_action=publish",
catch_response=True) as resp:
if resp.status_code >= 400:
self.client.auth = False
resp.raise_for_status()
# Set the thumbnail view
with self.client.get(
"/" + SITE_ID +
"/images/selectViewTemplate?templateId=atct_album_view",
catch_response=True) as resp:
if resp.status_code >= 400:
self.client.auth = False
resp.raise_for_status()
self.client.auth = False
def on_start(self):
self.create_site()
class CMSUser(HttpLocust):
task_set = SiteBrowser
min_wait = 10000
max_wait = 30000
class LocustRequestAnalysis(object):
def __init__(self, filename):
self.rows = []
self.filesizes = {}
with open(filename) as requests_file:
for row in csv.DictReader(requests_file):
self.rows.append(row)
for fname in os.listdir(IMG_DIR):
fstat = os.stat(os.path.join(IMG_DIR, fname))
self.filesizes[fname] = fstat.st_size
def report_data(self):
upload_data = {'count': 0, 'total_mb': 0,
'total_time': 0, 'average_per_mb': 0,
'min_per_mb': sys.maxint, 'max_per_mb': 0}
download_data = {'count': 0, 'total_mb': 0,
'total_time': 0, 'average_per_mb': 0,
'min_per_mb': sys.maxint, 'max_per_mb': 0}
listing_data = {}
for row in self.rows:
name = row['Name']
count = int(row['# requests'])
if count == 0:
continue
# An Upload
if name.endswith('/atct_edit') and '/Image/' in name:
fname = name.split('/')[4][6:]
size = self.filesizes.get(fname)
if not size:
logger.warn('Unknown filename {}: {}'.format(name, fname))
continue
else:
size = size / (1024.0 * 1024)
data = upload_data
# A Download
elif len(name.split('/')) >= 4 and '/images/' in name and '?' not in name:
size = int(row['Average Content Size']) / (1024 * 1024.0)
data = download_data
else:
if name.endswith('/images'):
listing_data['count'] = count
listing_data['average'] = int(row['Average response time'])
listing_data['median'] = int(row['Median response time'])
listing_data['min'] = int(row['Min response time'])
listing_data['max'] = int(row['Max response time'])
continue
# (Old Total Time + New Total Time) / (Total MB)
data['average_per_mb'] = ((
(data['total_mb'] * data['average_per_mb']) +
(int(row['Average response time']) * count)) /
(data['total_mb'] + size))
data['count'] += count
data['total_mb'] += size
data['total_time'] += count * int(row['Average response time'])
data['min_per_mb'] = min(data['min_per_mb'],
int(row["Min response time"]) / size)
data['max_per_mb'] = max(data['max_per_mb'],
int(row["Max response time"]) / size)
# report integer values (ms, MB)
for data in (download_data, upload_data):
for k, v in data.items():
data[k] = int(round(v))
return {'uploads': upload_data, 'downloads': download_data,
'listing': listing_data}