How to use _get_labels method in autotest

Best Python code snippet using autotest_python

__init__.py

Source:__init__.py Github

copy

Full Screen

...47 a way to do this automatically, then we could get rid of this, but all attempts to do this as part of fixture48 initialization, etc didn't work because the fixture is replaced for each phase of the test run (setup, run test)49 """50 caplog.handler.setFormatter(self.caplog)51 def _get_labels(self, metric: ExportRecord):52 return dict(filter(lambda label: not label[0].startswith('_'), metric.labels))53 def _find_metric(self,54 metric_type: Type,55 name: str,56 labels: Optional[Dict[str, str]] = None) -> Optional[ExportRecord]:57 labels = labels or {}58 def fail_no_match(msg: str, candidates: Optional[List[ExportRecord]] = None):59 if candidates is None:60 candidates = self.metrics_exporter.get_exported_metrics()61 msg = f"{msg}\n\nMetric:\n\t{name} {labels}\n\nRecorded {metric_type.__name__} metric(s):\n"62 if len(candidates) > 0:63 for m in candidates:64 msg = f"{msg}\t{m.instrument.name} {self._get_labels(m)}\n"65 else:66 msg = f"{msg}\t(none)"67 return msg68 if not self.collected:69 self.collect()70 candidates = []71 for metric in self.metrics_exporter.get_exported_metrics():72 m: ExportRecord = metric73 if type(m.instrument) != metric_type:74 continue75 candidates.append(m)76 if m.instrument.name == name:77 if self._get_labels(m) == labels:78 return m # exact match, return immediately79 pytest.fail(fail_no_match(f"No matching {metric_type.__name__} metric found!", candidates))80 def collect(self):81 self.collected = True82 for controller in self.metrics.meter_provider._controllers:83 if isinstance(controller, PushController):84 controller.tick()85 def get_metrics(self,86 type_filter: Callable[[Type], bool] = lambda v: True,87 name_filter: Callable[[str], bool] = lambda v: True,88 label_filter: Callable[[Dict[str, str]], bool] = lambda v: True,89 instrumentor_filter: Callable[[str], bool] = lambda v: True) -> List[90 Union[CounterInfo, ValueRecorderInfo]]:91 metrics = []92 for metric in self.metrics_exporter.get_exported_metrics():93 m: ExportRecord = metric94 if not type_filter(type(m.instrument)) or not name_filter(m.instrument.name) or \95 not label_filter(self._get_labels(m)) or not instrumentor_filter(m.instrument.meter.instrumentation_info.name):96 continue97 if type(m.instrument) == Counter:98 metrics.append(CounterInfo(m.instrument.name, m.aggregator.checkpoint, self._get_labels(m)))99 elif type(m.instrument) == ValueRecorder:100 metrics.append(ValueRecorderInfo(m.instrument.name,101 m.aggregator.checkpoint.min,102 m.aggregator.checkpoint.max,103 m.aggregator.checkpoint.sum,104 m.aggregator.checkpoint.count,105 self._get_labels(m)))106 else:107 # TODO: other metric types?108 pass109 return metrics110 def get_counters(self, name_filter: Callable[[str], bool] = lambda v: True,111 label_filter: Callable[[Dict[str, str]], bool] = lambda v: True) -> List[CounterInfo]:112 return self.get_metrics(type_filter=lambda t: t == Counter, name_filter=name_filter, label_filter=label_filter)113 def get_finished_spans(self, name_filter: Callable[[str], bool] = lambda v: True,114 attribute_filter: Callable[[Optional[Mapping[str, AttributeValue]]], bool] = lambda v: True,115 label_filter: Callable[[Dict[str, str]], bool] = lambda v: True) -> List[Span]:116 spans = []117 for span in self.span_exporter.get_finished_spans():118 if not name_filter(f"{span.qname}") or not attribute_filter(119 span.attributes) or not label_filter(span.labels):120 continue121 spans.append(span)122 return spans123 def get_value_recorders(self, name_filter: Callable[[str], bool] = lambda v: True,124 label_filter: Callable[[Dict[str, str]], bool] = lambda v: True) -> List[ValueRecorderInfo]:125 return self.get_metrics(type_filter=lambda t: t == ValueRecorder, name_filter=name_filter,126 label_filter=label_filter)127 def get_counter(self, name: str, labels: Optional[Dict[str, str]] = None) -> Optional[CounterInfo]:128 m = self._find_metric(Counter, name, labels)129 if m:130 return CounterInfo(m.instrument.name, m.aggregator.checkpoint, self._get_labels(m))131 else:132 return None133 def get_up_down_counter(self, name: str, labels: Optional[Dict[str, str]] = None) -> Optional[CounterInfo]:134 m = self._find_metric(UpDownCounter, name, labels)135 if m:136 return CounterInfo(m.instrument.name, m.aggregator.checkpoint, self._get_labels(m))137 else:138 return None139 def get_value_recorder(self, name: str, labels: Optional[Dict[str, str]] = None) -> Optional[ValueRecorderInfo]:140 m = self._find_metric(ValueRecorder, name, labels)141 if m:142 return ValueRecorderInfo(m.instrument.name,143 m.aggregator.checkpoint.min,144 m.aggregator.checkpoint.max,145 m.aggregator.checkpoint.sum,146 m.aggregator.checkpoint.count,147 self._get_labels(m))148 else:149 return None150 def get_gauge(self, name: str, labels: Optional[Dict[str, str]] = None) -> Optional[GaugeInfo]:151 m = self._find_metric(ValueObserver, name, labels)152 if m:153 return GaugeInfo(f"{m.instrument.name}.{name}",154 m.aggregator.checkpoint.min,155 m.aggregator.checkpoint.max,156 m.aggregator.checkpoint.sum,157 m.aggregator.checkpoint.last,158 m.aggregator.checkpoint.count,159 self._get_labels(m))160 else:161 return None162class JsonLogCaptureFormatter(JsonLogFormatter):163 def __init__(self):164 super(JsonLogCaptureFormatter, self).__init__()165 self.records = []166 def add_fields(self, log_record, record, message_dict):167 super(JsonLogCaptureFormatter, self).add_fields(log_record, record, message_dict)168 self.records.append(log_record)169 def find_records(self, f: Callable[[LogRecord], bool]) -> Iterator[LogRecord]:170 return filter(f, self.records)171 def get_record(self, f: Callable[[LogRecord], bool]) -> LogRecord:172 matching = list(filter(f, self.records))173 if len(matching) == 0:...

Full Screen

Full Screen

test_client_google.py

Source:test_client_google.py Github

copy

Full Screen

1import base642import responses3from io import BytesIO4from unittest import mock5from decouple import config6from PIL import Image7from engine.client_google_vision import (find_keywords,8 get_identified_labels,9 crop_image,10 vision_api)11from engine.tests.fixtures import vision_api_non_target, vision_api_target12def test_find_target_keywords():13 not_target = find_keywords(vision_api_non_target['responses'][0])14 target = find_keywords(vision_api_target['responses'][0])15 assert not_target is False16 assert target is True17@responses.activate18def test_get_google_vision_api_response():19 api_version = config('VISION_API_VERSION')20 token = config("VISION_TOKEN")21 with open('engine/tests/test_images/vision_test_image.jpg', 'rb') as image:22 image_content = image.read()23 base64_image = base64.b64encode(image_content).decode()24 responses.add(25 responses.POST,26 "https://vision.googleapis.com/{api_version}/images:annotate?"27 "key={token}".format(api_version=api_version, token=token),28 json=vision_api_non_target,29 status=20030 )31 labels = get_identified_labels(base64_image)32 assert labels == vision_api_non_target['responses'][0]33def test_crop_image():34 with open('engine/tests/test_images/vision_test_image.jpg', 'rb') as image:35 img = base64.b64encode(image.read()).decode()36 cropped_img = crop_image(img, prop=(0.5, 1.0))37 cropped_img_pil = Image.open(BytesIO(base64.b64decode(cropped_img)))38 expected_height = 42739 expected_width = 128040 assert cropped_img_pil.height == expected_height41 assert cropped_img_pil.width == expected_width42@mock.patch('engine.client_google_vision.BytesIO', return_value='img_obj')43@mock.patch('engine.client_google_vision.get_identified_labels')44@mock.patch('engine.client_google_vision.crop_image',45 return_value='cropped')46@mock.patch('engine.client_google_vision._prepare_image',47 return_value='prepared')48@mock.patch('engine.client_google_vision.requests.get')49def test_vision_api_pipeline(_get, _prepare_image, _crop_image, _get_labels,50 _bytes_io):51 _get_labels.return_value = {52 'labelAnnotations': [{'description': 'shoe'}]53 }54 content_mock = mock.MagicMock()55 content_mock.content = 'image_content'56 _get.return_value = content_mock57 is_target, b64_img = vision_api('image_url')58 _get.assert_called_once_with('image_url')59 _prepare_image.assert_called_once_with(content_mock)60 _crop_image.assert_called_once_with('prepared', (0, 1.0))61 _get_labels.assert_called_once_with('cropped')62 _bytes_io.assert_called_once_with('image_content')63 assert is_target is True64 assert b64_img == 'img_obj'65@mock.patch('engine.client_google_vision.BytesIO', return_value='img_obj')66@mock.patch('engine.client_google_vision.get_identified_labels')67@mock.patch('engine.client_google_vision.crop_image',68 return_value='cropped')69@mock.patch('engine.client_google_vision._prepare_image',70 return_value='prepared')71@mock.patch('engine.client_google_vision.requests.get')72def test_vision_api_pipeline_false_response(_get, _prepare_image, _crop_image,73 _get_labels, _bytes_io):74 response_mock = mock.MagicMock()75 response_mock.content = 'response content'76 _get.return_value = response_mock77 _get_labels.return_value = {78 'labelAnnotations': [{'description': 'not_target'}]79 }80 is_target, img_obj = vision_api('image_url')81 crop_image_calls = [82 mock.call('prepared', (0.0, 1.0)),83 mock.call('prepared', (0.5, 1.0)),84 mock.call('prepared', (0.75, 1.0)),85 mock.call('prepared', (0.5, 0.75))86 ]87 get_labels_calls = [mock.call('cropped') for i in range(3)]88 _get.assert_called_once_with('image_url')89 _prepare_image.assert_called_once_with(response_mock)90 _bytes_io.assert_called_once_with('response content')91 _crop_image.assert_has_calls(crop_image_calls)92 _get_labels.assert_has_calls(get_labels_calls)93 assert is_target is False94 assert img_obj is 'img_obj'95@mock.patch('engine.client_google_vision.BytesIO', return_value='img_obj')96@mock.patch('engine.client_google_vision.crop_image',97 return_value='cropped')98@mock.patch('engine.client_google_vision.get_identified_labels')99@mock.patch('engine.client_google_vision._prepare_image',100 return_value='prepared')101@mock.patch('engine.client_google_vision.requests.get')102def test_vision_api_pipeline_with_half_img(_get, _prepare_image, _get_labels,103 _crop_image, _bytes_io):104 response_mock = mock.MagicMock()105 response_mock.content = 'response content'106 _get.return_value = response_mock107 _get_labels.side_effect = [108 {'labelAnnotations': [{'description': 'not shoe'}]},109 {'labelAnnotations': [{'description': 'shoe'}]}110 ]111 is_target, img_obj = vision_api('image_url')112 get_labels_calls = [mock.call('prepared'), mock.call('cropped')]113 crop_image_calls = [mock.call('prepared', (0.0, 1.0)),114 mock.call('prepared', (0.5, 1.0))]115 _get.assert_called_once_with('image_url')116 _bytes_io.assert_called_once_with('response content')117 _prepare_image.assert_called_once_with(response_mock)118 _get_labels.call_args_list == get_labels_calls119 _crop_image.assert_has_calls(crop_image_calls)120 assert is_target is True...

Full Screen

Full Screen

samplers.py

Source:samplers.py Github

copy

Full Screen

...4import pandas as pd5import torch6import torch.utils.data7import torchvision8def _get_labels(dataset):9 if isinstance(dataset, torchvision.datasets.MNIST):10 return dataset.train_labels.tolist()11 elif isinstance(dataset, torchvision.datasets.ImageFolder):12 return [x[1] for x in dataset.imgs]13 elif isinstance(dataset, torchvision.datasets.DatasetFolder):14 return dataset.samples[:][1]15 elif isinstance(dataset, torch.utils.data.Subset):16 return dataset.dataset.imgs[:][1] # type: ignore17 elif isinstance(dataset, torch.utils.data.Dataset):18 return dataset.get_labels() # type: ignore19 else:20 raise NotImplementedError21class ImbalancedDatasetSampler(torch.utils.data.sampler.Sampler):22 """...

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