Best Python code snippet using avocado_python
builder.py
Source:builder.py  
1# StdLib2from collections import defaultdict3import os4from typing import List, Type, Union5# Internal deps6from .health_update import HealthUpdate7from .utils import (8    alerts_markdown,9    errors_markdown,10    warnings_markdown,11)12# External deps13from slack_sdk.models.blocks import (14    Block,15    DividerBlock,16    HeaderBlock,17    PlainTextObject,18    SectionBlock,19)20from slack_sdk.models.blocks.basic_components import MarkdownTextObject, Option21from slack_sdk.models.blocks.block_elements import StaticSelectElement22class Builder:23    """Builder for Slack text blocks."""24    ICONS={25        'Healthy': ':white_check_mark:',26        'Unhealthy': ':x:',27        'Warning': ':warning:',28        'Alert': ':exclamation:',29        'Unknown': ':question:',30    }31    def details(obj: Type[HealthUpdate]) -> List[Type[Block]]:32        blocks: List[Type[Block]] = []33        if obj.healthy_str != 'Healthy':34            blocks.append(DividerBlock())35            if obj.errors:36                blocks.append(37                    SectionBlock(38                        text = MarkdownTextObject(39                            text = errors_markdown(obj.errors)40                        )41                    )42                )43            if obj.warnings:44                blocks.append(45                    SectionBlock(46                        text = MarkdownTextObject(47                            text = warnings_markdown(obj.warnings)48                        )49                    )50                )51            if obj.alerts:52                blocks.append(53                    SectionBlock(54                        text = MarkdownTextObject(55                            text = alerts_markdown(obj.alerts)56                        )57                    )58                )59        return blocks60    def health(objs: Union[HealthUpdate, List[HealthUpdate]], details: bool=False) -> List[Type[Block]]:61        # Validate62        if isinstance(objs, HealthUpdate):63            objs = [objs]64        elif isinstance(objs, list):65            for obj in objs:66                if not isinstance(obj, HealthUpdate):67                    raise ValueError('all objects passed in list must be an instance of HealthUpdate')68        else:69            raise ValueError('objs variable must be an instance of HealthUpdate or List[HealthUpdate]')70        # Collect data71        icon = Builder.ICONS.get(obj.healthy_str, ':interrobang:')72        mrkdown = f'{icon} [{obj.kind}] *{obj.name}* state: *{obj.healthy_str}*.'73        # Building blocks74        blocks: List[Type[Block]] = []75        blocks.append(76            SectionBlock(77                text = MarkdownTextObject(78                    text = mrkdown79                )80            )81        )82        if details:83            blocks.extend(Builder.details(obj))84        return blocks85    def health_overview(objs: Type[HealthUpdate]) -> List[Type[Block]]:86        """A health_overview is a one-line list of states and their counts along with a list of namespaces that are unhealthy."""87        # Build the summary text88        collection = defaultdict(lambda: [])89        for ns in objs:90            collection[ns.healthy_str].append(ns)91        statuses = []92        if len(collection['Healthy']):93            statuses.append(f'healthy({len(collection["Healthy"])})')94        if len(collection['Unhealthy']):95            statuses.append(f'unhealthy({len(collection["Unhealthy"])})')96        if len(collection['Warning']):97            statuses.append(f'warning({len(collection["Warning"])})')98        if len(collection['Alert']):99            statuses.append(f'alert({len(collection["Alert"])})')100        # Building Blocks101        blocks: List[Type[Block]] = []102        blocks.append(103            HeaderBlock(104                text = PlainTextObject(105                    text = f':medical_symbol: Overall health: {", ".join(statuses)}'106                )107            )108        )109        if len(collection['Unhealthy']):110            blocks.append(DividerBlock())111            lines: List[str] = []112            for ns in collection['Unhealthy']:113                lines.append(f"*{ns.name}*: {len(ns.errors)} errors, {len(ns.warnings)} warnings.")114            # Build SelectBlock for more details115            blocks.append(116                SectionBlock(117                    text = MarkdownTextObject(118                        text = os.linesep.join(lines)119                    ),120                    accessory = StaticSelectElement(121                        placeholder = PlainTextObject(122                            text = 'More details...'123                        ),124                        #options=[{'text':{'type':'plain_text','text':ns.name,'value':ns.name}} for ns in collection['Unhealthy']],125                        options = [Option(text=ns.name, value=ns.name) for ns in collection['Unhealthy']],126                        action_id = 'health'127                    )128                )129            )130        return blocks131    def transition_msg(obj: HealthUpdate) -> List[Type[Block]]:132        """Create a Slack message for an Update stating a state transition."""133        # Gather info134        icon = Builder.ICONS.get(obj.healthy_str, ':interrobang"')135        text = f'{icon} [{obj.kind}] {obj.name} transitioned state: {obj.previous_healthy_str} -> {obj.healthy_str}'136        # Building blocks137        blocks: List[Type[Block]] = []138        blocks.append(139            HeaderBlock(140                text = PlainTextObject(141                    text = text142                )143            )144        )145        blocks.extend(Builder.details(obj))...health_update.py
Source:health_update.py  
...55    @property56    def healthy_raw(self) -> str:57        return self._healthy58    @property59    def healthy_str(self) -> str:60        return HealthUpdate.healthy_to_str(self._healthy)61    @property62    def kind(self) -> str:63        return self._kind64    @property65    def name(self) -> str:66        return self._name67    @property68    def namespace(self) -> str:69        return self._namespace70    @property71    def previous_healthy(self) -> Union[bool, None]:72        if self._previous_healthy == None:73            return None74        healthy = self._previous_healthy.lower()75        if healthy in ['true', 'warn', 'alert']:76            return True77        else:78            return False79    @property80    def previous_healthy_raw(self) -> Union[str, None]:81        return self._previous_healthy82    @previous_healthy_raw.setter83    def previous_healthy_raw(self, value: str) -> None:84        if isinstance(value, str):85            self._previous_healthy = value86    @property87    def previous_healthy_str(self) -> Union[str, None]:88        return HealthUpdate.healthy_to_str(self._previous_healthy)89    @property90    def tenant(self) -> str:91        return self._tenant92    @property93    def warnings(self) -> List[str]:94        return self._warnings95    def to_s(self) -> str:96        return f'[{self.kind}] {self.name} state: {self.healthy_str}'97    @staticmethod98    def healthy_to_str(healthy: str) -> str:99        """Because the API returns "True" if healthy,100        we want to translate that to something more101        readable by meat objects."""...test_healthupdate.py
Source:test_healthupdate.py  
1import copy2import pytest3from bmspy import HealthUpdate4test_params = [5    ('healthy_hupdate_dict', True, 'Healthy'),6    ('unhealthy_hupdate_dict', False, 'Unhealthy'),7    ('warning_hupdate_dict', True, 'Warning'),8    ('alert_hupdate_dict', True, 'Alert'),9    ('unknown_hupdate_dict', False, 'Unknown'),10]11@pytest.mark.parametrize('hupdate_dict,expected_healthy,expected_healthy_str', test_params)12def test_init(hupdate_dict, expected_healthy, expected_healthy_str, request):13    hupdate_dict = request.getfixturevalue(hupdate_dict)14    subj = HealthUpdate(hupdate_dict)15    assert subj.kind == hupdate_dict['kind']16    assert subj.name == hupdate_dict['name']17    assert subj.namespace == hupdate_dict['namespace']18    assert subj.healthy == expected_healthy19    assert subj.healthy_str == expected_healthy_str20    assert subj.errors == hupdate_dict['errors']21    assert subj.warnings == hupdate_dict['warnings']22    assert subj.alerts == hupdate_dict['alerts']23@pytest.mark.parametrize('field', ['healthy', 'kind', 'name'])24def test_init_validation(healthy_hupdate_dict, field):25    obj = copy.deepcopy(healthy_hupdate_dict)26    del(obj[field])27    with pytest.raises(KeyError) as e_info:...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
