How to use _create_metrics_plot_helper method in autotest

Best Python code snippet using autotest_python

graphing_utils.py

Source:graphing_utils.py Github

copy

Full Screen

...431 plot['errors'] = new_errors432 plot['y'], plot['errors'] = _normalize(plot['y'], plot['errors'],433 new_base_values,434 new_base_errors)435def _create_metrics_plot_helper(plot_info, extra_text=None):436 """437 Create a metrics plot of the given plot data.438 plot_info: a MetricsPlot object.439 extra_text: text to show at the uppper-left of the graph440 TODO(showard): move some/all of this logic into methods on MetricsPlot441 """442 query = plot_info.query_dict['__main__']443 cursor = readonly_connection.cursor()444 cursor.execute(query)445 if not cursor.rowcount:446 raise NoDataError('query did not return any data')447 rows = cursor.fetchall()448 # "transpose" rows, so columns[0] is all the values from the first column,449 # etc.450 columns = zip(*rows)451 plots = []452 labels = [str(label) for label in columns[0]]453 needs_resort = (cursor.description[0][0] == 'kernel')454 # Collect all the data for the plot455 col = 1456 while col < len(cursor.description):457 y = columns[col]458 label = cursor.description[col][0]459 col += 1460 if (col < len(cursor.description) and461 'errors-' + label == cursor.description[col][0]):462 errors = columns[col]463 col += 1464 else:465 errors = None466 if needs_resort:467 y = _resort(labels, y)468 if errors:469 errors = _resort(labels, errors)470 x = [index for index, value in enumerate(y) if value is not None]471 if not x:472 raise NoDataError('No data for series ' + label)473 y = [y[i] for i in x]474 if errors:475 errors = [errors[i] for i in x]476 plots.append({477 'label': label,478 'x': x,479 'y': y,480 'errors': errors481 })482 if needs_resort:483 labels = _resort(labels, labels)484 # Normalize the data if necessary485 normalize_to = plot_info.normalize_to486 if normalize_to == 'first' or normalize_to.startswith('x__'):487 if normalize_to != 'first':488 baseline = normalize_to[3:]489 try:490 baseline_index = labels.index(baseline)491 except ValueError:492 raise ValidationError({493 'Normalize' : 'Invalid baseline %s' % baseline494 })495 for plot in plots:496 if normalize_to == 'first':497 plot_index = 0498 else:499 try:500 plot_index = plot['x'].index(baseline_index)501 # if the value is not found, then we cannot normalize502 except ValueError:503 raise ValidationError({504 'Normalize' : ('%s does not have a value for %s'505 % (plot['label'], normalize_to[3:]))506 })507 base_values = [plot['y'][plot_index]] * len(plot['y'])508 if plot['errors']:509 base_errors = [plot['errors'][plot_index]] * len(plot['errors'])510 plot['y'], plot['errors'] = _normalize(plot['y'], plot['errors'],511 base_values,512 None or base_errors)513 elif normalize_to.startswith('series__'):514 base_series = normalize_to[8:]515 _normalize_to_series(plots, base_series)516 # Call the appropriate function to draw the line or bar plot517 if plot_info.is_line:518 figure, area_data = _create_line(plots, labels, plot_info)519 else:520 figure, area_data = _create_bar(plots, labels, plot_info)521 # TODO(showard): extract these magic numbers to named constants522 if extra_text:523 text_y = .95 - .0075 * len(plots)524 figure.text(.1, text_y, extra_text, size='xx-small')525 return (figure, area_data)526def create_metrics_plot(query_dict, plot_type, inverted_series, normalize_to,527 drilldown_callback, extra_text=None):528 plot_info = MetricsPlot(query_dict, plot_type, inverted_series,529 normalize_to, drilldown_callback)530 figure, area_data = _create_metrics_plot_helper(plot_info, extra_text)531 return _create_image_html(figure, area_data, plot_info)532def _get_hostnames_in_bucket(hist_data, bucket):533 """\534 Get all the hostnames that constitute a particular bucket in the histogram.535 hist_data: list containing tuples of (hostname, pass_rate)536 bucket: tuple containing the (low, high) values of the target bucket537 """538 return [hostname for hostname, pass_rate in hist_data539 if bucket[0] <= pass_rate < bucket[1]]540def _create_qual_histogram_helper(plot_info, extra_text=None):541 """\542 Create a machine qualification histogram of the given data.543 plot_info: a QualificationHistogram544 extra_text: text to show at the upper-left of the graph545 TODO(showard): move much or all of this into methods on546 QualificationHistogram547 """548 cursor = readonly_connection.cursor()549 cursor.execute(plot_info.query)550 if not cursor.rowcount:551 raise NoDataError('query did not return any data')552 # Lists to store the plot data.553 # hist_data store tuples of (hostname, pass_rate) for machines that have554 # pass rates between 0 and 100%, exclusive.555 # no_tests is a list of machines that have run none of the selected tests556 # no_pass is a list of machines with 0% pass rate557 # perfect is a list of machines with a 100% pass rate558 hist_data = []559 no_tests = []560 no_pass = []561 perfect = []562 # Construct the lists of data to plot563 for hostname, total, good in cursor.fetchall():564 if total == 0:565 no_tests.append(hostname)566 continue567 if good == 0:568 no_pass.append(hostname)569 elif good == total:570 perfect.append(hostname)571 else:572 percentage = 100.0 * good / total573 hist_data.append((hostname, percentage))574 interval = plot_info.interval575 bins = range(0, 100, interval)576 if bins[-1] != 100:577 bins.append(bins[-1] + interval)578 figure, height = _create_figure(_SINGLE_PLOT_HEIGHT)579 subplot = figure.add_subplot(1, 1, 1)580 # Plot the data and get all the bars plotted581 _,_, bars = subplot.hist([data[1] for data in hist_data],582 bins=bins, align='left')583 bars += subplot.bar([-interval], len(no_pass),584 width=interval, align='center')585 bars += subplot.bar([bins[-1]], len(perfect),586 width=interval, align='center')587 bars += subplot.bar([-3 * interval], len(no_tests),588 width=interval, align='center')589 buckets = [(bin, min(bin + interval, 100)) for bin in bins[:-1]]590 # set the x-axis range to cover all the normal bins plus the three "special"591 # ones - N/A (3 intervals left), 0% (1 interval left) ,and 100% (far right)592 subplot.set_xlim(-4 * interval, bins[-1] + interval)593 subplot.set_xticks([-3 * interval, -interval] + bins + [100 + interval])594 subplot.set_xticklabels(['N/A', '0%'] +595 ['%d%% - <%d%%' % bucket for bucket in buckets] +596 ['100%'], rotation=90, size='small')597 # Find the coordinates on the image for each bar598 x = []599 y = []600 for bar in bars:601 x.append(bar.get_x())602 y.append(bar.get_height())603 f = subplot.plot(x, y, linestyle='None')[0]604 upper_left_coords = f.get_transform().transform(zip(x, y))605 bottom_right_coords = f.get_transform().transform(606 [(x_val + interval, 0) for x_val in x])607 # Set the title attributes608 titles = ['%d%% - <%d%%: %d machines' % (bucket[0], bucket[1], y_val)609 for bucket, y_val in zip(buckets, y)]610 titles.append('0%%: %d machines' % len(no_pass))611 titles.append('100%%: %d machines' % len(perfect))612 titles.append('N/A: %d machines' % len(no_tests))613 # Get the hostnames for each bucket in the histogram614 names_list = [_get_hostnames_in_bucket(hist_data, bucket)615 for bucket in buckets]616 names_list += [no_pass, perfect]617 if plot_info.filter_string:618 plot_info.filter_string += ' AND '619 # Construct the list of drilldown parameters to be passed when the user620 # clicks on the bar.621 params = []622 for names in names_list:623 if names:624 hostnames = ','.join(_quote(hostname) for hostname in names)625 hostname_filter = 'hostname IN (%s)' % hostnames626 full_filter = plot_info.filter_string + hostname_filter627 params.append({'type': 'normal',628 'filterString': full_filter})629 else:630 params.append({'type': 'empty'})631 params.append({'type': 'not_applicable',632 'hosts': '<br />'.join(no_tests)})633 area_data = [dict(left=ulx, top=height - uly,634 right=brx, bottom=height - bry,635 title=title, callback=plot_info.drilldown_callback,636 callback_arguments=param_dict)637 for (ulx, uly), (brx, bry), title, param_dict638 in zip(upper_left_coords, bottom_right_coords, titles, params)]639 # TODO(showard): extract these magic numbers to named constants640 if extra_text:641 figure.text(.1, .95, extra_text, size='xx-small')642 return (figure, area_data)643def create_qual_histogram(query, filter_string, interval, drilldown_callback,644 extra_text=None):645 plot_info = QualificationHistogram(query, filter_string, interval,646 drilldown_callback)647 figure, area_data = _create_qual_histogram_helper(plot_info, extra_text)648 return _create_image_html(figure, area_data, plot_info)649def create_embedded_plot(model, update_time):650 """\651 Given an EmbeddedGraphingQuery object, generate the PNG image for it.652 model: EmbeddedGraphingQuery object653 update_time: 'Last updated' time654 """655 params = pickle.loads(model.params)656 extra_text = 'Last updated: %s' % update_time657 if model.graph_type == 'metrics':658 plot_info = MetricsPlot(query_dict=params['queries'],659 plot_type=params['plot'],660 inverted_series=params['invert'],661 normalize_to=None,662 drilldown_callback='')663 figure, areas_unused = _create_metrics_plot_helper(plot_info,664 extra_text)665 elif model.graph_type == 'qual':666 plot_info = QualificationHistogram(667 query=params['query'], filter_string=params['filter_string'],668 interval=params['interval'], drilldown_callback='')669 figure, areas_unused = _create_qual_histogram_helper(plot_info,670 extra_text)671 else:672 raise ValueError('Invalid graph_type %s' % model.graph_type)673 image, bounding_box_unused = _create_png(figure)674 return image675_cache_timeout = global_config.global_config.get_config_value(676 'AUTOTEST_WEB', 'graph_cache_creation_timeout_minutes')677def handle_plot_request(id, max_age):...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful