Best Python code snippet using Testify_python
stock_reconciliation.py
Source:stock_reconciliation.py  
...36		if data.index(self.head_row) != 0:37			head_row_no = data.index(self.head_row)38			data = data[head_row_no:]39			self.reconciliation_json = json.dumps(data)40		def _get_msg(row_num, msg):41			return _("Row # {0}: ").format(row_num+head_row_no+2) + msg42		self.validation_messages = []43		item_warehouse_combinations = []44		# validate no of rows45		rows = data[1:]46		if len(rows) > 100:47			msgprint(_("""Sorry! We can only allow upto 100 rows for Stock Reconciliation."""),48				raise_exception=True)49		for row_num, row in enumerate(rows):50			# find duplicates51			if [row[0], row[1]] in item_warehouse_combinations:52				self.validation_messages.append(_get_msg(row_num, _("Duplicate entry")))53			else:54				item_warehouse_combinations.append([row[0], row[1]])55			self.validate_item(row[0], row_num+head_row_no+2)56			# validate warehouse57			if not frappe.db.get_value("Warehouse", row[1]):58				self.validation_messages.append(_get_msg(row_num, _("Warehouse not found in the system")))59			# if both not specified60			if row[2] in ["", None] and row[3] in ["", None]:61				self.validation_messages.append(_get_msg(row_num,62					_("Please specify either Quantity or Valuation Rate or both")))63			# do not allow negative quantity64			if flt(row[2]) < 0:65				self.validation_messages.append(_get_msg(row_num,66					_("Negative Quantity is not allowed")))67			# do not allow negative valuation68			if flt(row[3]) < 0:69				self.validation_messages.append(_get_msg(row_num,70					_("Negative Valuation Rate is not allowed")))71		# throw all validation messages72		if self.validation_messages:73			for msg in self.validation_messages:74				msgprint(msg)75			raise frappe.ValidationError76	def validate_item(self, item_code, row_num):77		from erpnext.stock.doctype.item.item import validate_end_of_life, \78			validate_is_stock_item, validate_cancelled_item79		# using try except to catch all validation msgs and display together80		try:81			item = frappe.get_doc("Item", item_code)82			if not item:83				raise frappe.ValidationError, (_("Item: {0} not found in the system").format(item_code))...solver.py
Source:solver.py  
...79                    )80                    self.solvesys.addWhereDragged(p, wrkpln=wp, group=group)81                continue82            e.create_slvs_data(self.solvesys, group=group)83        def _get_msg():84            msg = "Initialize entities:"85            for e in context.scene.sketcher.entities.all:86                msg += "\n  - {}".format(e)87            return msg88        logger.debug(_get_msg())89        # Initialize Constraints90        for c in context.scene.sketcher.constraints.all:91            if hasattr(c, "sketch") and c.sketch:92                group = self._get_group(c.sketch)93            else:94                group = self.group_3d95            if self.report:96                c.failed = False97            # Store a index-constraint mapping98            from collections.abc import Iterable99            indices = c.create_slvs_data(self.solvesys, group=group)100            self._store_constraint_indices(101                c, indices if isinstance(indices, Iterable) else (indices,)102            )103        def _get_msg():104            msg = "Initialize constraints:"105            for c in context.scene.sketcher.constraints.all:106                msg += "\n  - {}".format(c)107            return msg108        logger.debug(_get_msg())109    def tweak(self, entity, pos):110        logger.debug("tweak: {} to: {}".format(entity, pos))111        self.tweak_entity = entity112        # NOTE: there should be a difference between 2d coords or 3d location...113        self.tweak_pos = pos114    def is_active(self, e):115        if e.fixed:116            return False117        return e.is_active(self.sketch)118    # NOTE: When solving not everything might be relevant...119    # An approach could be to find all constraints of a sketch and all neccesary entities120    # and only inizialize them121    # def dummy():122    # wp = None123    # if context.scene.sketcher.active_workplane_i == -1:124    #     group = self.group_3d125    # else:126    #     wp = context.scene.sketcher.active_workplane127    #     # i = context.scene.sketcher.entities.get_local_index(wp.slvs_index)128    #     # group = i + 2129    #     group = group_wp130    #131    # constraints = self.get_constraints(context, wp)132    #133    # entities = []134    # for c in constraints:135    #     # ensure entities are initialized136    #     for e in c.entities(): # should be recursive!137    #         if e not in entities:138    #             entities.append(e)139    #140    #     c.create_slvs_data(solvesys)141    # def get_constraints(self, context, wp):142    #     constraints = []143    #     for c in context.scene.sketcher.constraints.all:144    #         if wp and not hasattr(c, "wp"):145    #             continue146    #         if hasattr(c, "wp") and c.wp != wp:147    #             continue  # c.is_active(group)148    #         constraints.append(c)149    #     return constraints150    def solve(self, report=True):151        self.report = report152        self._init_slvs_data()153        if self.all:154            sse = self.context.scene.sketcher.entities155            sketches = [None, *sse.sketches]156        else:157            sketches = [self.sketch,]158        for sketch in sketches:159            g = self._get_group(sketch)160            retval = self.solvesys.solve(161                group=g,162                reportFailed=report,163                findFreeParams=False,164            )165            # NOTE: For some reason solve() might return undocumented values,166            # Clamp result value to 4167            if retval > 3:168                logger.debug("Solver returned undocumented value: {}".format(retval))169                retval = 4170            self.result = bpyEnum(solver_state_items, index=retval)171            if report and sketch:172                sketch.solver_state = self.result.index173            if retval != 0:174                self.ok = False175                # Store sketch failures176                self.failed_sketches.append(sketch)177            logger.info(self.result.description)178            fails = self.solvesys.Failed179            if report and fails:180                for i in fails:181                    if i == self.tweak_constraint:182                        continue183                    constr = self.constraints[i]184                    constr.failed = True185                def _get_msg():186                    msg = "Failed constraints:"187                    for i in fails:188                        constr = self.constraints[i]189                        msg += "\n  - {}".format(constr)190                    return msg191                logger.debug(_get_msg())192        msg = ""193        for e in self.entities:194            # Skip entities that belong to a failed sketch195            if hasattr(e, "sketch") and  e.sketch in self.failed_sketches:196                continue197            # TODO: skip entities that aren't in active group198            msg += "\n - " + str(e)199            e.update_from_slvs(self.solvesys)200        if msg:201            logger.debug("Update entities from solver:" + msg)202        return self.ok203def solve_system(context, sketch=None):204    solver = Solver(context, sketch)205    return solver.solve()helpmd_lint.py
Source:helpmd_lint.py  
...36        if self.helpmd.help_md is None or self.dp.dockerfile is None:37            self.cancel("Help file or Dockerfile was not found")38    def tearDown(self, *args, **kwargs):39        pass40    def _get_msg(self, msg):41        return msg + " is missing in help file."42    def test_helpmd_image_name(self):43        container_name = self.dp.get_docker_specific_env("NAME=")44        if container_name:45            self.assertTrue(self.helpmd.get_image_name(container_name[0].split('=')[1]),46                            msg="%s The correct format is %% MEMCACHED(1)" % self._get_msg("Image name"))47    def test_helpmd_maintainer_name(self):48        maintainer_name = self.dp.get_specific_label("maintainer")49        if maintainer_name:50            self.assertTrue(self.helpmd.get_maintainer_name(maintainer_name[0]),51                            msg="%s The correct format is '%% User Name'. Or you have a typo in the help file." % self._get_msg("maintainer"))52    def test_helpmd_name(self):53        self.assertTrue(self.helpmd.get_tag("NAME"),54                        msg=self._get_msg("NAME section"))55    def test_helpmd_description(self):56        self.assertTrue(self.helpmd.get_tag("DESCRIPTION"),57                        msg=self._get_msg("DESCRIPTION section"))58    def test_helpmd_usage(self):59        self.assertTrue(self.helpmd.get_tag("USAGE"),60                        msg=self._get_msg("USAGE section"))61    def test_helpmd_environment_variables(self):62        self.assert_to_warn(self.assertTrue, self.helpmd.get_tag("ENVIRONMENT VARIABLES"),63                            msg=self._get_msg("ENVIRONMENT VARIABLES section"))64    def test_helpmd_security_implications(self):65        if self.dp.get_docker_expose():66            self.assertTrue(self.helpmd.get_tag("SECURITY IMPLICATIONS"),...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!!
