Best Python code snippet using grail_python
nice_checkbox.py
Source:nice_checkbox.py  
1from math import floor, sqrt, ceil2from Qt import QtWidgets, QtCore, QtGui3from openpype.style import get_objected_colors4class NiceCheckbox(QtWidgets.QFrame):5    stateChanged = QtCore.Signal(int)6    clicked = QtCore.Signal()7    _checked_bg_color = None8    _unchecked_bg_color = None9    _checker_color = None10    _checker_hover_color = None11    def __init__(self, checked=False, draw_icons=False, parent=None):12        super(NiceCheckbox, self).__init__(parent)13        self.setObjectName("NiceCheckbox")14        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)15        self.setSizePolicy(16            QtWidgets.QSizePolicy.Fixed,17            QtWidgets.QSizePolicy.Fixed18        )19        self._checked = checked20        if checked:21            checkstate = QtCore.Qt.Checked22        else:23            checkstate = QtCore.Qt.Unchecked24        self._checkstate = checkstate25        self._is_tristate = False26        self._draw_icons = draw_icons27        self._animation_timer = QtCore.QTimer(self)28        self._animation_timeout = 629        self._fixed_width_set = False30        self._fixed_height_set = False31        self._current_step = None32        self._steps = 2133        self._middle_step = 1134        self.set_steps(self._steps)35        self._checker_margins_divider = 036        self._pressed = False37        self._under_mouse = False38        self.icon_scale_factor = sqrt(2) / 239        icon_path_stroker = QtGui.QPainterPathStroker()40        icon_path_stroker.setCapStyle(QtCore.Qt.RoundCap)41        icon_path_stroker.setJoinStyle(QtCore.Qt.RoundJoin)42        self.icon_path_stroker = icon_path_stroker43        self._animation_timer.timeout.connect(self._on_animation_timeout)44        self._base_size = QtCore.QSize(90, 50)45        self._load_colors()46    @classmethod47    def _load_colors(cls):48        if cls._checked_bg_color is not None:49            return50        colors_data = get_objected_colors()51        colors_info = colors_data["nice-checkbox"]52        cls._checked_bg_color = colors_info["bg-checked"].get_qcolor()53        cls._unchecked_bg_color = colors_info["bg-unchecked"].get_qcolor()54        cls._checker_color = colors_info["bg-checker"].get_qcolor()55        cls._checker_hover_color = colors_info["bg-checker-hover"].get_qcolor()56    @property57    def checked_bg_color(self):58        return self._checked_bg_color59    @property60    def unchecked_bg_color(self):61        return self._unchecked_bg_color62    @property63    def checker_color(self):64        return self._checker_color65    @property66    def checker_hover_color(self):67        return self._checker_hover_color68    def setTristate(self, tristate=True):69        if self._is_tristate != tristate:70            self._is_tristate = tristate71    def set_draw_icons(self, draw_icons=None):72        if draw_icons is None:73            draw_icons = not self._draw_icons74        if draw_icons == self._draw_icons:75            return76        self._draw_icons = draw_icons77        self.repaint()78    def sizeHint(self):79        height = self.fontMetrics().height()80        width = self.get_width_hint_by_height(height)81        return QtCore.QSize(width, height)82    def get_width_hint_by_height(self, height):83        return (84            height / self._base_size.height()85        ) * self._base_size.width()86    def get_height_hint_by_width(self, width):87        return (88            width / self._base_size.width()89        ) * self._base_size.height()90    def setFixedHeight(self, *args, **kwargs):91        self._fixed_height_set = True92        super(NiceCheckbox, self).setFixedHeight(*args, **kwargs)93        if not self._fixed_width_set:94            width = self.get_width_hint_by_height(self.height())95            self.setFixedWidth(width)96    def setFixedWidth(self, *args, **kwargs):97        self._fixed_width_set = True98        super(NiceCheckbox, self).setFixedWidth(*args, **kwargs)99        if not self._fixed_height_set:100            height = self.get_height_hint_by_width(self.width())101            self.setFixedHeight(height)102    def setFixedSize(self, *args, **kwargs):103        self._fixed_height_set = True104        self._fixed_width_set = True105        super(NiceCheckbox, self).setFixedSize(*args, **kwargs)106    def steps(self):107        return self._steps108    def set_steps(self, steps):109        if steps < 2:110            steps = 2111        # Make sure animation is stopped112        if self._animation_timer.isActive():113            self._animation_timer.stop()114        # Set steps and set current step by current checkstate115        self._steps = steps116        diff = steps % 2117        self._middle_step = (int(steps - diff) / 2) + diff118        if self._checkstate == QtCore.Qt.Checked:119            self._current_step = self._steps120        elif self._checkstate == QtCore.Qt.Unchecked:121            self._current_step = 0122        else:123            self._current_step = self._middle_step124    def checkState(self):125        return self._checkstate126    def isChecked(self):127        return self._checked128    def setCheckState(self, state):129        if self._checkstate == state:130            return131        self._checkstate = state132        if state == QtCore.Qt.Checked:133            self._checked = True134        elif state == QtCore.Qt.Unchecked:135            self._checked = False136        self.stateChanged.emit(self.checkState())137        if self._animation_timer.isActive():138            self._animation_timer.stop()139        if self.isVisible() and self.isEnabled():140            # Start animation141            self._animation_timer.start(self._animation_timeout)142        else:143            # Do not animate change if is disabled144            if state == QtCore.Qt.Checked:145                self._current_step = self._steps146            elif state == QtCore.Qt.Unchecked:147                self._current_step = 0148            else:149                self._current_step = self._middle_step150            self.repaint()151    def setChecked(self, checked):152        if checked == self._checked:153            return154        if checked:155            checkstate = QtCore.Qt.Checked156        else:157            checkstate = QtCore.Qt.Unchecked158        self.setCheckState(checkstate)159    def nextCheckState(self):160        if self._checkstate == QtCore.Qt.Unchecked:161            if self._is_tristate:162                return QtCore.Qt.PartiallyChecked163            return QtCore.Qt.Checked164        if self._checkstate == QtCore.Qt.Checked:165            return QtCore.Qt.Unchecked166        if self._checked:167            return QtCore.Qt.Unchecked168        return QtCore.Qt.Checked169    def mousePressEvent(self, event):170        if event.buttons() & QtCore.Qt.LeftButton:171            self._pressed = True172            self.repaint()173        super(NiceCheckbox, self).mousePressEvent(event)174    def mouseReleaseEvent(self, event):175        if self._pressed and not event.buttons() & QtCore.Qt.LeftButton:176            self._pressed = False177            if self.rect().contains(event.pos()):178                self.setCheckState(self.nextCheckState())179                self.clicked.emit()180                event.accept()181                return182        super(NiceCheckbox, self).mouseReleaseEvent(event)183    def mouseMoveEvent(self, event):184        if self._pressed:185            under_mouse = self.rect().contains(event.pos())186            if under_mouse != self._under_mouse:187                self._under_mouse = under_mouse188                self.repaint()189        super(NiceCheckbox, self).mouseMoveEvent(event)190    def enterEvent(self, event):191        self._under_mouse = True192        if self.isEnabled():193            self.repaint()194        super(NiceCheckbox, self).enterEvent(event)195    def leaveEvent(self, event):196        self._under_mouse = False197        if self.isEnabled():198            self.repaint()199        super(NiceCheckbox, self).leaveEvent(event)200    def _on_animation_timeout(self):201        if self._checkstate == QtCore.Qt.Checked:202            if self._current_step == self._steps:203                self._animation_timer.stop()204                return205            self._current_step += 1206        elif self._checkstate == QtCore.Qt.Unchecked:207            if self._current_step == 0:208                self._animation_timer.stop()209                return210            self._current_step -= 1211        else:212            if self._current_step < self._middle_step:213                self._current_step += 1214            elif self._current_step > self._middle_step:215                self._current_step -= 1216            if self._current_step == self._middle_step:217                self._animation_timer.stop()218        self.repaint()219    @staticmethod220    def steped_color(color1, color2, offset_ratio):221        red_dif = (222            color1.red() - color2.red()223        )224        green_dif = (225            color1.green() - color2.green()226        )227        blue_dif = (228            color1.blue() - color2.blue()229        )230        red = int(color2.red() + (231            red_dif * offset_ratio232        ))233        green = int(color2.green() + (234            green_dif * offset_ratio235        ))236        blue = int(color2.blue() + (237            blue_dif * offset_ratio238        ))239        return QtGui.QColor(red, green, blue)240    def paintEvent(self, event):241        frame_rect = QtCore.QRect(self.rect())242        if frame_rect.width() < 0 or frame_rect.height() < 0:243            return244        painter = QtGui.QPainter(self)245        painter.setRenderHint(QtGui.QPainter.Antialiasing)246        # Draw inner background247        if self._current_step == self._steps:248            bg_color = self.checked_bg_color249        elif self._current_step == 0:250            bg_color = self.unchecked_bg_color251        else:252            offset_ratio = self._current_step / self._steps253            # Animation bg254            bg_color = self.steped_color(255                self.checked_bg_color,256                self.unchecked_bg_color,257                offset_ratio258            )259        margins_ratio = self._checker_margins_divider260        if margins_ratio > 0:261            size_without_margins = int(262                (frame_rect.height() / margins_ratio) * (margins_ratio - 2)263            )264            size_without_margins -= size_without_margins % 2265            margin_size_c = ceil(266                frame_rect.height() - size_without_margins267            ) / 2268        else:269            size_without_margins = frame_rect.height()270            margin_size_c = 0271        checkbox_rect = QtCore.QRect(272            frame_rect.x() + margin_size_c,273            frame_rect.y() + margin_size_c,274            frame_rect.width() - (margin_size_c * 2),275            frame_rect.height() - (margin_size_c * 2)276        )277        if checkbox_rect.width() > checkbox_rect.height():278            radius = floor(checkbox_rect.height() / 2)279        else:280            radius = floor(checkbox_rect.width() / 2)281        painter.setPen(QtCore.Qt.transparent)282        painter.setBrush(bg_color)283        painter.drawRoundedRect(checkbox_rect, radius, radius)284        # Draw checker285        checker_size = size_without_margins - (margin_size_c * 2)286        area_width = (287            checkbox_rect.width()288            - (margin_size_c * 2)289            - checker_size290        )291        if self._current_step == 0:292            x_offset = 0293        else:294            x_offset = (area_width / self._steps) * self._current_step295        pos_x = checkbox_rect.x() + x_offset + margin_size_c296        pos_y = checkbox_rect.y() + margin_size_c297        checker_rect = QtCore.QRect(pos_x, pos_y, checker_size, checker_size)298        under_mouse = self.isEnabled() and self._under_mouse299        if under_mouse:300            checker_color = self.checker_hover_color301        else:302            checker_color = self.checker_color303        painter.setBrush(checker_color)304        painter.drawEllipse(checker_rect)305        if self._draw_icons:306            painter.setBrush(bg_color)307            icon_path = self._get_icon_path(painter, checker_rect)308            painter.drawPath(icon_path)309        # Draw shadow overlay310        if not self.isEnabled():311            level = 33312            alpha = 127313            painter.setPen(QtCore.Qt.transparent)314            painter.setBrush(QtGui.QColor(level, level, level, alpha))315            painter.drawRoundedRect(checkbox_rect, radius, radius)316        painter.end()317    def _get_icon_path(self, painter, checker_rect):318        self.icon_path_stroker.setWidth(checker_rect.height() / 5)319        if self._current_step == self._steps:320            return self._get_enabled_icon_path(painter, checker_rect)321        if self._current_step == 0:322            return self._get_disabled_icon_path(painter, checker_rect)323        if self._current_step == self._middle_step:324            return self._get_middle_circle_path(painter, checker_rect)325        disabled_step = self._steps - self._current_step326        enabled_step = self._steps - disabled_step327        half_steps = self._steps + 1 - ((self._steps + 1) % 2)328        if enabled_step > disabled_step:329            return self._get_enabled_icon_path(330                painter, checker_rect, enabled_step, half_steps331            )332        else:333            return self._get_disabled_icon_path(334                painter, checker_rect, disabled_step, half_steps335            )336    def _get_middle_circle_path(self, painter, checker_rect):337        width = self.icon_path_stroker.width()338        path = QtGui.QPainterPath()339        path.addEllipse(checker_rect.center(), width, width)340        return path341    def _get_enabled_icon_path(342        self, painter, checker_rect, step=None, half_steps=None343    ):344        fifteenth = checker_rect.height() / 15345        # Left point346        p1 = QtCore.QPoint(347            checker_rect.x() + (5 * fifteenth),348            checker_rect.y() + (9 * fifteenth)349        )350        # Middle bottom point351        p2 = QtCore.QPoint(352            checker_rect.center().x(),353            checker_rect.y() + (11 * fifteenth)354        )355        # Top right point356        p3 = QtCore.QPoint(357            checker_rect.x() + (10 * fifteenth),358            checker_rect.y() + (5 * fifteenth)359        )360        if step is not None:361            multiplier = (half_steps - step)362            p1c = p1 - checker_rect.center()363            p2c = p2 - checker_rect.center()364            p3c = p3 - checker_rect.center()365            p1o = QtCore.QPoint(366                (p1c.x() / half_steps) * multiplier,367                (p1c.y() / half_steps) * multiplier368            )369            p2o = QtCore.QPoint(370                (p2c.x() / half_steps) * multiplier,371                (p2c.y() / half_steps) * multiplier372            )373            p3o = QtCore.QPoint(374                (p3c.x() / half_steps) * multiplier,375                (p3c.y() / half_steps) * multiplier376            )377            p1 -= p1o378            p2 -= p2o379            p3 -= p3o380        path = QtGui.QPainterPath(p1)381        path.lineTo(p2)382        path.lineTo(p3)383        return self.icon_path_stroker.createStroke(path)384    def _get_disabled_icon_path(385        self, painter, checker_rect, step=None, half_steps=None386    ):387        center_point = QtCore.QPointF(388            checker_rect.width() / 2, checker_rect.height() / 2389        )390        offset = (391            (center_point + QtCore.QPointF(0, 0)) / 2392        ).x() / 4 * 5393        if step is not None:394            diff = center_point.x() - offset395            diff_offset = (diff / half_steps) * (half_steps - step)396            offset += diff_offset397        line1_p1 = QtCore.QPointF(398            checker_rect.topLeft().x() + offset,399            checker_rect.topLeft().y() + offset,400        )401        line1_p2 = QtCore.QPointF(402            checker_rect.bottomRight().x() - offset,403            checker_rect.bottomRight().y() - offset404        )405        line2_p1 = QtCore.QPointF(406            checker_rect.bottomLeft().x() + offset,407            checker_rect.bottomLeft().y() - offset408        )409        line2_p2 = QtCore.QPointF(410            checker_rect.topRight().x() - offset,411            checker_rect.topRight().y() + offset412        )413        path = QtGui.QPainterPath()414        path.moveTo(line1_p1)415        path.lineTo(line1_p2)416        path.moveTo(line2_p1)417        path.lineTo(line2_p2)...pipeline_database.py
Source:pipeline_database.py  
1from typing import Optional2from overrides import overrides3from octo_pipeline_python.common.database import Database4from octo_pipeline_python.pipeline.pipeline_action import PipelineAction5from octo_pipeline_python.pipeline.pipeline_context import PipelineContext6from octo_pipeline_python.pipeline.pipeline_description import \7    PipelineDescription8from octo_pipeline_python.utils.logger import logger9class PipelineDatabase(Database):10    def __init__(self, context: PipelineContext, pipeline_description: PipelineDescription):11        super().__init__(context.working_dir, context.name, f"{context.name}.pipeline")12        self.__context = context13        self.__description = pipeline_description14        self.__current_step_idx = 015        self.__dirty = False16        self.__disabled_steps = []17        if self.contains("step"):18            self.__current_step_idx = self.get("step")19        if self.contains("dirty"):20            self.__dirty = self.get("dirty")21        else:22            while (len(self.__description.actions) - 1) > self.__current_step_idx and \23                    self.__context.surrounding not in self.__description.actions[self.__current_step_idx].surroundings:24                self.__current_step_idx += 125        if self.contains("disabled-steps"):26            self.__disabled_steps = self.get("disabled-steps")27    def mark_dirty(self) -> None:28        """29        Marks the pipeline as dirty30        :return:31        """32        self.__dirty = True33        self.commit("dirty", self.__dirty, False)34    def reset_dirtiness(self) -> None:35        """36        Unmarks the dirtiness of the pipeline37        :return:38        """39        self.__dirty = False40        self.commit("dirty", self.__dirty, False)41    def step_next(self) -> None:42        """43        Move the actions step pointer forward and store it44        :return:45        """46        last_idx = self.__current_step_idx47        while (len(self.__description.actions) - 1) > self.__current_step_idx:48            self.__current_step_idx += 149            if (len(self.__description.actions) - 1) > self.__current_step_idx and \50                    self.__context.surrounding in self.__description.actions[self.__current_step_idx].surroundings:51                break52            else:53                logger.info(f"[{self.tag}] Skipping step [{self.__current_step_idx}. "54                            f"{self.__description.actions[self.__current_step_idx].action_type}]")55        if last_idx != self.__current_step_idx and \56                self.__context.surrounding in self.__description.actions[self.__current_step_idx].surroundings:57            logger.info(f"[{self.tag}] Advanced to step "58                        f"[{self.__current_step_idx}. "59                        f"{self.__description.actions[self.__current_step_idx].action_type}]")60        elif last_idx == self.__current_step_idx == (len(self.__description.actions) - 1):61            self.__current_step_idx = len(self.__description.actions)62            logger.info(f"[{self.tag}] Reached last step")63        self.commit("step", self.__current_step_idx, False)64    def step_previous(self) -> None:65        """66        Move the action step pointer backwards and store it67        :return:68        """69        last_idx = self.__current_step_idx70        while self.__current_step_idx > 0:71            self.__current_step_idx -= 172            if self.__context.surrounding in self.__description.actions[self.__current_step_idx].surroundings:73                break74        if last_idx != self.__current_step_idx and \75                self.__context.surrounding in self.__description.actions[self.__current_step_idx].surroundings:76            logger.info(f"[{self.tag}] Advanced to step "77                        f"[{self.__current_step_idx}. "78                        f"{self.__description.actions[self.__current_step_idx].action_type}]")79        else:80            self.__current_step_idx = 081            logger.info(f"[{self.tag}] Reached first step")82        self.commit("step", self.__current_step_idx, False)83    def disable_step(self,84                     action: str,85                     backend: Optional[str] = None,86                     command: Optional[str] = None) -> None:87        """88        Disables a step and saves it on the DB89        :param action:90        :param backend:91        :param command:92        :return:93        """94        # Check if the step is already disabled95        step_found = False96        for disabled_step in self.__disabled_steps:97            if disabled_step["action"] == action:98                if backend and 'backend' in disabled_step and backend != disabled_step['backend']:99                    continue100                if command and 'command' in disabled_step and command != disabled_step['command']:101                    continue102                logger.info(f"Step [{action}] is already disabled")103                step_found = True104                break105        if not step_found:106            logged_msg = f"Disabling step [{action}]"107            if backend:108                logged_msg += f" for backend [{backend}]"109            if command:110                logged_msg += f" for command [{command}]"111            logger.info(logged_msg)112            disabled_step = {113                "action": action114            }115            if backend:116                disabled_step["backend"] = backend117            if command:118                disabled_step["command"] = command119            self.__disabled_steps.append(disabled_step)120            self.commit("disabled-steps", self.__disabled_steps, True)121    def enable_step(self,122                    action: str,123                    backend: Optional[str] = None,124                    command: Optional[str] = None) -> None:125        for idx, disabled_step in enumerate(self.__disabled_steps):126            if disabled_step["action"] == action:127                if backend and 'backend' in disabled_step and backend != disabled_step['backend']:128                    continue129                if command and 'command' in disabled_step and command != disabled_step['command']:130                    continue131                logged_msg = f"Enabling step [{action}]"132                if backend:133                    logged_msg += f" for backend [{backend}]"134                if command:135                    logged_msg += f" for command [{command}]"136                logger.info(logged_msg)137                del self.__disabled_steps[idx]138                self.commit("disabled-steps", self.__disabled_steps, True)139                break140    def is_step_disabled(self,141                         action: str,142                         backend: Optional[str] = None,143                         command: Optional[str] = None) -> bool:144        for disabled_step in self.__disabled_steps:145            if disabled_step["action"] == action:146                if backend and 'backend' in disabled_step and backend != disabled_step['backend']:147                    continue148                if command and 'command' in disabled_step and command != disabled_step['command']:149                    continue150                return True151        return False152    @overrides153    def reset(self) -> None:154        self.__current_step_idx = 0155        self.__dirty = False156        super().reset()157    @property158    def current_step(self) -> Optional[PipelineAction]:159        """160        Getter for the current step161        :return:162        """163        if self.__current_step_idx < len(self.__description.actions) and \164                self.__context.surrounding in self.__description.actions[self.__current_step_idx].surroundings:165            return self.__description.actions[self.__current_step_idx]166        return None167    @property168    def current_step_idx(self) -> int:169        """170        Getter for the current step index171        :return:172        """173        return self.__current_step_idx174    @property175    def has_steps(self) -> bool:176        """177        Getter for if theres more steps or not178        :return:179        """180        return self.__current_step_idx < len(self.__description.actions)181    @property182    def dirty(self) -> bool:183        """184        Getter for if the pipeline is dirty185        :return:186        """...test_steps.py
Source:test_steps.py  
...7from grail import step8from tests.utils import validate_method_output9class TestStepDisabling(TestCase):10    @step11    def disabled_step(self):12        print 'Some data'13    @step(log_output=True)14    def disabled_step_params(self):15        print 'Some data after params'16    def setUp(self):17        grail.settings.disable_steps = True18    def tearDown(self):19        grail.settings.disable_steps = False20    def test_step_disabling(self):21        validate_method_output(self.disabled_step, u'Some data')22    def test_step_disabling_with_params(self):23        validate_method_output(self.disabled_step_params, u'Some data after params')24class TestStepLogic(TestCase):25    @step(step_group=True)...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!!
