Best Python code snippet using avocado_python
test_storylib.py
Source:test_storylib.py  
...22        story = self.story(data=Data.filter(None))23        story.add_slide(Slide(Step(Data.filter(None))))24        story.add_slide(Slide(Step(Data.filter('record.Function !== "Defense"'))))25        return story26    def get_vpd(self) -> str:27        """A method for returning a test Vizzu-Player data."""28        return (29            "{"30            + '"data": {"filter": null}, '31            + '"slides": ['32            + '[{"filter": null}], '33            + '[{"filter": record => { return (record.Function !== "Defense") }}]'34            + "]}"35        )36    def get_html(self) -> str:37        """A method for returning a test Story html output."""38        return DISPLAY_TEMPLATE.format(39            id="1234567",40            vizzu_story=VIZZU_STORY,41            vizzu_player_data=self.get_vpd(),42            chart_size="",43            chart_features="",44            chart_events="",45        )46    def get_html_with_size(self) -> str:47        """A method for returning a test Story html output with size values."""48        return DISPLAY_TEMPLATE.format(49            id="1234567",50            vizzu_story=VIZZU_STORY,51            vizzu_player_data=self.get_vpd(),52            chart_size="vizzuPlayer.style.cssText = 'width: 800px;height: 480px;'",53            chart_features="",54            chart_events="",55        )56class TestStoryInit(unittest.TestCase):57    """A class for testing Story() class' __init__()."""58    def test_init_if_no_data_was_passed(self) -> None:59        """A method for testing Story().__init__() if no data was passed."""60        with self.assertRaises(TypeError):61            Story()  # type: ignore  # pylint: disable=no-value-for-parameter62    def test_init_if_no_data_was_set(self) -> None:63        """A method for testing Story().__init__() if no data was set."""64        with self.assertRaises(TypeError):65            Story(data={})  # type: ignore66    def test_init_if_not_valid_data_was_set(self) -> None:67        """A method for testing Story().__init__() if not valid data was set."""68        with self.assertRaises(TypeError):69            Story(data={"filter": None})  # type: ignore70    def test_init_if_data_was_set(self) -> None:71        """A method for testing Story().__init__() if data was set."""72        self.assertEqual(73            Story(data=Data.filter(None)), {"data": {"filter": None}, "slides": []}74        )75    def test_init_if_no_style_was_set(self) -> None:76        """A method for testing Story().__init__() if no style was set."""77        self.assertEqual(78            Story(data=Data.filter(None), style={}),  # type: ignore79            {"data": {"filter": None}, "slides": []},80        )81    def test_init_if_not_valid_style_was_set(self) -> None:82        """A method for testing Story().__init__() if not valid style was set."""83        with self.assertRaises(TypeError):84            Story(data=Data.filter(None), style={"style": None})  # type: ignore85    def test_init_if_style_was_set(self) -> None:86        """A method for testing Story().__init__() if data was set."""87        self.assertEqual(88            Story(data=Data.filter(None), style=Style(None)),89            {"data": {"filter": None}, "style": None, "slides": []},90        )91class TestStoryAddSlide(unittest.TestCase):92    """A class for testing Story() class' add_slide()."""93    def test_add_slide_if_no_slide_was_set(self) -> None:94        """A method for testing Story().add_slide() if no slide was set."""95        story = Story(data=Data.filter(None))96        with self.assertRaises(TypeError):97            story.add_slide({})  # type: ignore98    def test_add_slide_if_not_valid_slide_was_set(self) -> None:99        """A method for testing Story().add_slide() if not valid slide was set."""100        story = Story(data=Data.filter(None))101        with self.assertRaises(TypeError):102            story.add_slide({"filter": None})  # type: ignore103    def test_add_slide_if_slides_were_set(self) -> None:104        """A method for testing Story().add_slide() if slides were set."""105        story = Story(data=Data.filter(None))106        story.add_slide(Slide(Step(Data.filter(None))))107        story.add_slide(Slide(Step(Data.filter(None))))108        self.assertEqual(109            story,110            {111                "data": {"filter": None},112                "slides": [[{"filter": None}], [{"filter": None}]],113            },114        )115class TestStoryHtml(TestHtml, unittest.TestCase):116    """A class for testing Story() class' html releated methods."""117    def setUp(self):118        self.test_dir = os.path.dirname(os.path.realpath(__file__))119    def tearDown(self):120        file_list = glob.glob(self.test_dir + "/.test.*")121        for file_path in file_list:122            os.remove(file_path)123    def story(self, *args, **kwargs):124        """A method for returning Chart()."""125        return Story(*args, **kwargs)126    def test_export_to_html(self) -> None:127        """A method for testing Story().export_to_html()."""128        with unittest.mock.patch(129            "ipyvizzustory.storylib.story.uuid.uuid4", return_value=self130        ):131            test_html = self.test_dir + "/.test.test_export_to_html.html"132            story = self.get_story()133            story.export_to_html(test_html)134            with open(test_html, "r", encoding="utf8") as file_desc:135                test_html_content = file_desc.read()136            self.assertEqual(137                test_html_content,138                self.get_html(),139            )140    def test_repr_html(self) -> None:141        """A method for testing Story()._repr_html_()."""142        with unittest.mock.patch(143            "ipyvizzustory.storylib.story.uuid.uuid4", return_value=self144        ):145            self.assertEqual(146                self.get_story()._repr_html_(),  # pylint: disable=protected-access147                self.get_html(),148            )149    def test_to_html(self) -> None:150        """A method for testing Story().to_html()."""151        with unittest.mock.patch(152            "ipyvizzustory.storylib.story.uuid.uuid4", return_value=self153        ):154            self.assertEqual(155                self.get_story().to_html(),156                self.get_html(),157            )158    def test_to_html_with_size(self) -> None:159        """A method for testing Story().to_html() with size."""160        with unittest.mock.patch(161            "ipyvizzustory.storylib.story.uuid.uuid4", return_value=self162        ):163            story = self.get_story()164            story.set_size(width=None, height=None)165            self.assertEqual(166                story.to_html(),167                DISPLAY_TEMPLATE.format(168                    id="1234567",169                    vizzu_story=VIZZU_STORY,170                    vizzu_player_data=self.get_vpd(),171                    chart_size="",172                    chart_features="",173                    chart_events="",174                ),175            )176    def test_to_html_with_size_width(self) -> None:177        """A method for testing Story().to_html() with size/width."""178        with unittest.mock.patch(179            "ipyvizzustory.storylib.story.uuid.uuid4", return_value=self180        ):181            story = self.get_story()182            story.set_size(width="800px", height=None)183            self.assertEqual(184                story.to_html(),185                DISPLAY_TEMPLATE.format(186                    id="1234567",187                    vizzu_story=VIZZU_STORY,188                    vizzu_player_data=self.get_vpd(),189                    chart_size="vizzuPlayer.style.cssText = 'width: 800px;'",190                    chart_features="",191                    chart_events="",192                ),193            )194    def test_to_html_with_size_height(self) -> None:195        """A method for testing Story().to_html() with size/height."""196        with unittest.mock.patch(197            "ipyvizzustory.storylib.story.uuid.uuid4", return_value=self198        ):199            story = self.get_story()200            story.set_size(width=None, height="480px")201            self.assertEqual(202                story.to_html(),203                DISPLAY_TEMPLATE.format(204                    id="1234567",205                    vizzu_story=VIZZU_STORY,206                    vizzu_player_data=self.get_vpd(),207                    chart_size="vizzuPlayer.style.cssText = 'height: 480px;'",208                    chart_features="",209                    chart_events="",210                ),211            )212    def test_to_html_with_size_width_and_height(self) -> None:213        """A method for testing Story().to_html() with size/width and height."""214        with unittest.mock.patch(215            "ipyvizzustory.storylib.story.uuid.uuid4", return_value=self216        ):217            story = self.get_story()218            story.set_size(width="800px", height="480px")219            self.assertEqual(220                story.to_html(),221                self.get_html_with_size(),222            )223    def test_to_html_with_feature(self) -> None:224        """A method for testing Story().to_html() with feature."""225        with unittest.mock.patch(226            "ipyvizzustory.storylib.story.uuid.uuid4", return_value=self227        ):228            story = self.get_story()229            story.set_feature("tooltip", True)230            story.set_feature("tooltip", True)231            self.assertEqual(232                story.to_html(),233                DISPLAY_TEMPLATE.format(234                    id="1234567",235                    vizzu_story=VIZZU_STORY,236                    vizzu_player_data=self.get_vpd(),237                    chart_size="",238                    chart_features=(239                        "chart.feature('tooltip', true);"240                        + f"\n{DISPLAY_INDENT * 3}"241                        + "chart.feature('tooltip', true);"242                    ),243                    chart_events="",244                ),245            )246    def test_to_html_with_event(self) -> None:247        """A method for testing Story().to_html() with event."""248        with unittest.mock.patch(249            "ipyvizzustory.storylib.story.uuid.uuid4", return_value=self250        ):251            story = self.get_story()252            handler = """253                let Year = parseFloat(event.data.text);254                if (!isNaN(Year) && Year > 1950 && Year < 2020 && Year % 5 !== 0) {255                    event.preventDefault();256                }257                """258            story.add_event("plot-axis-label-draw", handler)259            story.add_event("plot-axis-label-draw", handler)260            self.assertEqual(261                story.to_html(),262                DISPLAY_TEMPLATE.format(263                    id="1234567",264                    vizzu_story=VIZZU_STORY,265                    vizzu_player_data=self.get_vpd(),266                    chart_size="",267                    chart_features="",268                    chart_events=(269                        "chart.on('plot-axis-label-draw', "270                        + f"event => {{{' '.join(handler.split())}}});"271                        + f"\n{DISPLAY_INDENT * 3}"272                        + "chart.on('plot-axis-label-draw', "273                        + f"event => {{{' '.join(handler.split())}}});"274                    ),275                ),...sensor.py
Source:sensor.py  
...13def get_temp(T_OFFSET=10):14    return 9 * (sensor.read_temperature() - T_OFFSET) / 5 + 3215def get_humid(H_OFFSET=-10):16    return sensor.read_humidity() - H_OFFSET17def get_vpd(T, H):18    A = -1.044e419    B = -11.2920    C = -2.7e-221    D = 1.289e-522    E = -2.478e-923    F = 6.45624    25    T += 459.6726    kpa_c = 6.89475729 27    vp = np.exp(A/T + B + C*T + D*T**2 + E*T**3 + F*np.log(T)) * (1 - H / 100)28    vp *= kpa_c 29    return vp30if __name__ == '__main__':31    config = configparser.ConfigParser()32    config.read('/home/pi/kindbot/config.ini')33    T_OFFSET = int(config['DAYTIME']['T_OFFSET'])34    H_OFFSET = int(config['DAYTIME']['H_OFFSET'])35    S_INTERVAL = int(config['DAYTIME']['S_INTERVAL'])36    T = get_temp(T_OFFSET=T_OFFSET)37    H = get_humid(H_OFFSET=H_OFFSET)38    VPD = get_vpd(T, H)39    conn = sqlite3.connect(config['PATHS']['DB_PATH'], timeout=30000)40    c = conn.cursor()41    c.execute("""insert into environ values (?, ?, ?, ?)""", (str(datetime.now()).split('.')[0], round(T, 2), round(H, 2), round(VPD, 2)))42    conn.commit()43    c.close()...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!!
