Best Python code snippet using pytest
youtube.py
Source:youtube.py
1from Screens.Screen import Screen2from Screens.HelpMenu import HelpableScreen3from Components.ActionMap import ActionMap, HelpableActionMap4from Components.ConfigList import ConfigListScreen5from Components.Label import Label6from Components.Sources.StaticText import StaticText7from Components.config import config, ConfigSubsection, ConfigYesNo, ConfigText, getConfigListEntry8import vbcfg9from __init__ import _10config.plugins.youtubetv = ConfigSubsection()11config.plugins.youtubetv.showhelp = ConfigYesNo(default = False)12config.plugins.youtubetv.uri = ConfigText(default = "http://www.youtube.com/tv", visible_width = 50, fixed_size = False)13vbcfg.g_youtubetv_cfg = config.plugins.youtubetv14class YoutubeTVWindow(Screen, HelpableScreen):15 skin = """16 <screen name="YoutubeTVWindow" position="center,center" size="550,160" title="Start YouTube TV" >17 <widget name="infomation" position="5,0" size="540,80" valign="center" halign="center" font="Regular;20" />18 <widget name="startdesc" position="10,80" size="395,40" valign="center" font="Regular;20" />19 <widget name="helpdesc" position="10,120" size="395,40" valign="center" font="Regular;20" />20 <ePixmap pixmap="skin_default/buttons/green.png" position="400,80" size="140,40" alphatest="on" />21 <ePixmap pixmap="skin_default/buttons/yellow.png" position="400,120" size="140,40" alphatest="on" />22 <widget source="key_green" render="Label" position="400,80" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />23 <widget source="key_yellow" render="Label" position="400,120" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" foregroundColor="#ffffff" transparent="1" />24 </screen>25 """26 def __init__(self, session):27 Screen.__init__(self, session)28 HelpableScreen.__init__(self)29 self["actions"] = ActionMap(["WizardActions", "DirectionActions", "OkCancelActions","ColorActions", "EPGSelectActions",], {30 "cancel": self.keyCancel,31 "red" : self.keyCancel,32 "green" : self.keyGreen,33 "yellow": self.keyYellow,34 },-2)35 self["key_green"] = StaticText(_("Start"))36 self["key_yellow"] = StaticText(_("Help"))37 self["infomation"] = Label()38 self["startdesc"] = Label()39 self["helpdesc"] = Label()40 self.onLayoutFinish.append(self.layoutFinished)41 def layoutFinished(self):42 self.setTitle(_('Start YouTube TV'))43 self["infomation"].setText(_("YouTube TV is a new way to watch YouTube videos on Vu+"))44 self["startdesc" ].setText(_("* Start YouTube TV"))45 self["helpdesc" ].setText(_("* RC Help"))46 def setHelpModeActions(self):47 self.helpList = []48 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions", {49 "ok" : (self.keyPass, _("Play ther selected the video")),50 "cancel": (self.keyPass, _("Exit the YouTube TV")),51 })52 self["EventViewActions"] = HelpableActionMap(self, "EventViewActions", {53 "pageUp" : (self.keyPass, _("Move up")),54 "pageDown" : (self.keyPass, _("Move down")),55 "prevEvent" : (self.keyPass, _("Move left")),56 "nextEvent" : (self.keyPass, _("Move right")),57 })58 self["EPGSelectActions"] = HelpableActionMap(self, "EPGSelectActions", {59 "info" : (self.keyPass, _("Search a video")),60 "nextService" : (self.keyPass, _("Skip forward 10 sec")),61 "prevService" : (self.keyPass, _("Skip backward 10 sec")),62 })63 self["MediaPlayerActions"] = HelpableActionMap(self, "MediaPlayerActions", {64 "play" : (self.keyPass, _("Play current video")),65 "pause" : (self.keyPass, _("Pause current video")),66 "stop" : (self.keyPass, _("Stop current video")),67 })68 self["ColorActions"] = HelpableActionMap(self, "ColorActions", {69 "red" : (self.keyPass, _("Back")),70 })71 self.showHelp()72 def keyPass(self):73 pass74 def keyCancel(self):75 config.plugins.youtubetv.showhelp.cancel()76 self.close(False)77 def keyGreen(self):78 config.plugins.youtubetv.showhelp.save()79 config.plugins.youtubetv.save()80 config.plugins.save()81 vbcfg.g_youtubetv_cfg = config.plugins.youtubetv82 self.close(True)83 def keyYellow(self):84 self.setHelpModeActions()85 def keyBlue(self):86 if config.plugins.youtubetv.showhelp.value == True :87 config.plugins.youtubetv.showhelp.setValue(False)88 else: config.plugins.youtubetv.showhelp.setValue(True)89class YoutubeTVSettings(ConfigListScreen, Screen):90 skin= """91 <screen position="center,center" size="600,140" title="YouTube TV Settings">92 <widget name="config" position="0,0" size="600,100" scrollbarMode="showOnDemand" />93 <ePixmap pixmap="skin_default/buttons/red.png" position="310,100" size="140,40" alphatest="on" />94 <ePixmap pixmap="skin_default/buttons/green.png" position="150,100" size="140,40" alphatest="on" />95 <widget source="key_red" render="Label" position="310,100" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />96 <widget source="key_green" render="Label" position="150,100" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />97 </screen>98 """99 def __init__(self, session):100 self.session = session101 self.menulist = []102 Screen.__init__(self, session)103 ConfigListScreen.__init__(self, self.menulist)104 self["actions"] = ActionMap(["OkCancelActions", "ColorActions",], {105 "ok" : self.keyGreen,106 "green" : self.keyGreen,107 "red" : self.keyRed,108 "cancel" : self.keyRed,109 }, -2)110 self["key_red"] = StaticText(_("Cancel"))111 self["key_green"] = StaticText(_("Save"))112 self.makeConfigList()113 self.onLayoutFinish.append(self.layoutFinished)114 def layoutFinished(self):115 self.setTitle(_('YouTube TV Settings'))116 def keyGreen(self):117 config.plugins.youtubetv.showhelp.save()118 config.plugins.youtubetv.uri.save()119 config.plugins.youtubetv.save()120 config.plugins.save()121 vbcfg.g_youtubetv_cfg = config.plugins.youtubetv122 self.close()123 def keyRed(self):124 config.plugins.youtubetv.showhelp.cancel()125 config.plugins.youtubetv.uri.cancel()126 self.close()127 def keyLeft(self):128 ConfigListScreen.keyLeft(self)129 def keyRight(self):130 ConfigListScreen.keyRight(self)131 def makeConfigList(self):132 self.menulist = []133 entryUri = getConfigListEntry(_("YouTube TV URL"), config.plugins.youtubetv.uri)134 entryShowHelp = getConfigListEntry(_("Do not show YouTube TV Starter again"), config.plugins.youtubetv.showhelp)135 self.menulist.append(entryUri)136 self.menulist.append(entryShowHelp)137 self["config"].list = self.menulist...
mako_renderer.py
Source:mako_renderer.py
...36 exec plugin_code in plugin_module.__dict__37 return plugin_module38def out(msg):39 print >> sys.stderr, msg40def showhelp():41 out('mako-renderer.py [-o out] [-m cache] [-P preprocessed_input] [-d dict] [-d dict...]'42 ' [-t template] [-w preprocessed_output]')43def main(argv):44 got_input = False45 module_directory = None46 preprocessed_output = None47 dictionary = {}48 json_dict = {}49 got_output = False50 plugins = []51 output_name = None52 got_preprocessed_input = False53 output_merged = None54 try:55 opts, args = getopt.getopt(argv, 'hM:m:d:o:p:t:P:w:')56 except getopt.GetoptError:57 out('Unknown option')58 showhelp()59 sys.exit(2)60 for opt, arg in opts:61 if opt == '-h':62 out('Displaying showhelp')63 showhelp()64 sys.exit()65 elif opt == '-o':66 if got_output:67 out('Got more than one output')68 showhelp()69 sys.exit(3)70 got_output = True71 output_name = arg72 elif opt == '-m':73 if module_directory is not None:74 out('Got more than one cache directory')75 showhelp()76 sys.exit(4)77 module_directory = arg78 elif opt == '-M':79 if output_merged is not None:80 out('Got more than one output merged path')81 showhelp()82 sys.exit(5)83 output_merged = arg84 elif opt == '-P':85 assert not got_preprocessed_input86 assert json_dict == {}87 sys.path.insert(88 0,89 os.path.abspath(90 os.path.join(os.path.dirname(sys.argv[0]), 'plugins')))91 with open(arg, 'r') as dict_file:92 dictionary = pickle.load(dict_file)93 got_preprocessed_input = True94 elif opt == '-d':95 assert not got_preprocessed_input96 with open(arg, 'r') as dict_file:97 bunch.merge_json(json_dict, yaml.load(dict_file.read()))98 elif opt == '-p':99 plugins.append(import_plugin(arg))100 elif opt == '-w':101 preprocessed_output = arg102 if not got_preprocessed_input:103 for plugin in plugins:104 plugin.mako_plugin(json_dict)105 if output_merged:106 with open(output_merged, 'w') as yaml_file:107 yaml_file.write(yaml.dump(json_dict))108 for k, v in json_dict.items():109 dictionary[k] = bunch.to_bunch(v)110 if preprocessed_output:111 with open(preprocessed_output, 'w') as dict_file:112 pickle.dump(dictionary, dict_file)113 cleared_dir = False114 for arg in args:115 got_input = True116 with open(arg) as f:117 srcs = list(yaml.load_all(f.read()))118 for src in srcs:119 if isinstance(src, basestring):120 assert len(srcs) == 1121 template = Template(src,122 filename=arg,123 module_directory=module_directory,124 lookup=TemplateLookup(directories=['.']))125 with open(output_name, 'w') as output_file:126 template.render_context(Context(output_file, **dictionary))127 else:128 # we have optional control data: this template represents129 # a directory130 if not cleared_dir:131 if not os.path.exists(output_name):132 pass133 elif os.path.isfile(output_name):134 os.unlink(output_name)135 else:136 shutil.rmtree(output_name, ignore_errors=True)137 cleared_dir = True138 items = []139 if 'foreach' in src:140 for el in dictionary[src['foreach']]:141 if 'cond' in src:142 args = dict(dictionary)143 args['selected'] = el144 if not eval(src['cond'], {}, args):145 continue146 items.append(el)147 assert items148 else:149 items = [None]150 for item in items:151 args = dict(dictionary)152 args['selected'] = item153 item_output_name = os.path.join(154 output_name,155 Template(src['output_name']).render(**args))156 if not os.path.exists(os.path.dirname(item_output_name)):157 os.makedirs(os.path.dirname(item_output_name))158 template = Template(159 src['template'],160 filename=arg,161 module_directory=module_directory,162 lookup=TemplateLookup(directories=['.']))163 with open(item_output_name, 'w') as output_file:164 template.render_context(Context(output_file, **args))165 if not got_input and not preprocessed_output:166 out('Got nothing to do')167 showhelp()168if __name__ == '__main__':...
main.py
Source:main.py
1##2# main.py3# Copyright 2012, Vincent Petithory4#5# This file is part of the TMX Rasterizer.6#7# Redistribution and use in source and binary forms, with or without8# modification, are permitted provided that the following conditions are met:9#10# 1. Redistributions of source code must retain the above copyright notice,11# this list of conditions and the following disclaimer.12#13# 2. Redistributions in binary form must reproduce the above copyright14# notice, this list of conditions and the following disclaimer in the15# documentation and/or other materials provided with the distribution.16#17# THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR18# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF19# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO20# EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,22# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS23# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,24# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR25# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF26# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.27##28import sys29sys.path.append('./../')30sys.path.append('./../libtiled')31sys.path.append('./../QtProperty')32sys.path.append('./../libqt5')33sys.path.append('./../tiled')34sys.path.append('./../plugins')35from tiled_global import Int2, Float236from pyqtcore import QStringList37from tmxrasterizer import TmxRasterizer38from PyQt5.QtGui import (39 QGuiApplication40)41from PyQt5.QtCore import (42 qWarning,43 QCoreApplication44)45class CommandLineOptions():46 def __init__(self):47 self.showHelp = False48 self.showVersion = False49 self.fileToOpen = ''50 self.fileToSave = ''51 self.scale = 1.052 self.tileSize = 053 self.useAntiAliasing = False54 self.ignoreVisibility = False55 self.layersToHide = QStringList()56def showHelp():57 # TODO: Make translatable58 qWarning(59 "Usage:\n"60 " tmxrasterizer [options] [input file] [output file]\n"61 "\n"62 "Options:\n"63 " -h --help : Display this help\n"64 " -v --version : Display the version\n"65 " -s --scale SCALE : The scale of the output image (default: 1)\n"66 " -t --tilesize SIZE : The requested size in pixels at which a tile is rendered\n"67 " Overrides the --scale option\n"68 " -a --anti-aliasing : Smooth the output image using anti-aliasing\n"69 " --ignore-visibility : Ignore all layer visibility flags in the map file, and render all\n"70 " layers in the output (default is to omit invisible layers)\n"71 " --hide-layer : Specifies a layer to omit from the output image\n"72 " Can be repeated to hide multiple layers\n")73def showVersion():74 qWarning("TMX Map Rasterizer" + QCoreApplication.applicationVersion())75def parseCommandLineArguments(options):76 arguments = sys.argv77 i = 178 while i < len(arguments):79 arg = arguments[i]80 if (arg == "--help") or arg == "-h":81 options.showHelp = True82 elif (arg == "--version"83 or arg == "-v"):84 options.showVersion = True85 elif (arg == "--scale"86 or arg == "-s"):87 i += 188 if (i >= len(arguments)):89 options.showHelp = True90 else:91 options.scale, scaleIsDouble = Float2(arguments[i])92 if (not scaleIsDouble):93 qWarning(arguments[i] + ": the specified scale is not a number.")94 options.showHelp = True95 elif (arg == "--tilesize"96 or arg == "-t"):97 i += 198 if (i >= len(arguments)):99 options.showHelp = True100 else:101 options.tileSize, tileSizeIsInt = Int2(arguments[i])102 if (not tileSizeIsInt):103 qWarning(arguments[i] + ": the specified tile size is not an integer.")104 options.showHelp = True105 elif (arg == "--hide-layer"):106 i += 1107 if (i >= len(arguments)):108 options.showHelp = True109 else:110 options.layersToHide.append(arguments[i])111 elif (arg == "--anti-aliasing"112 or arg == "-a"):113 options.useAntiAliasing = True114 elif arg == "--ignore-visibility":115 options.ignoreVisibility = True116 elif arg == '':117 options.showHelp = True118 elif arg[0] == '-':119 qWarning("Unknown option" + arg)120 options.showHelp = True121 elif options.fileToOpen == '':122 options.fileToOpen = arg123 elif options.fileToSave == '':124 options.fileToSave = arg125 else:126 # All args are already defined. Show help.127 options.showHelp = True128 129 i += 1130def main(argv):131 a = QGuiApplication(argv)132 a.setOrganizationDomain("mapeditor.org")133 a.setApplicationName("TmxRasterizer")134 a.setApplicationVersion("1.0")135 options = CommandLineOptions()136 parseCommandLineArguments(options)137 if (options.showVersion):138 showVersion()139 return 0140 if (options.showHelp or options.fileToOpen=='' or options.fileToSave==''):141 showHelp()142 return 0143 if (options.scale <= 0.0 and options.tileSize <= 0):144 showHelp()145 return 0146 w = TmxRasterizer()147 w.setAntiAliasing(options.useAntiAliasing)148 w.setIgnoreVisibility(options.ignoreVisibility)149 w.setLayersToHide(options.layersToHide)150 if (options.tileSize > 0):151 w.setTileSize(options.tileSize)152 elif (options.scale > 0.0):153 w.setScale(options.scale)154 return w.render(options.fileToOpen, options.fileToSave)155if __name__ == '__main__':...
_mako_renderer.py
Source:_mako_renderer.py
...33# TODO(lidiz) find a better way for plugins to reference each other34sys.path.append(os.path.join(PROJECT_ROOT, 'tools', 'buildgen', 'plugins'))35def out(msg: str) -> None:36 print(msg, file=sys.stderr)37def showhelp() -> None:38 out('mako-renderer.py [-o out] [-m cache] [-P preprocessed_input] [-d dict] [-d dict...]'39 ' [-t template] [-w preprocessed_output]')40def render_template(template: Template, context: Context) -> None:41 """Render the mako template with given context.42 Prints an error template to indicate where and what in the template caused43 the render failure.44 """45 try:46 template.render_context(context)47 except:48 out(exceptions.text_error_template().render())49 raise50def main(argv: List[str]) -> None:51 got_input = False52 module_directory = None53 preprocessed_output = None54 dictionary = {}55 json_dict = {}56 got_output = False57 output_name = None58 got_preprocessed_input = False59 output_merged = None60 try:61 opts, args = getopt.getopt(argv, 'hM:m:o:t:P:')62 except getopt.GetoptError:63 out('Unknown option')64 showhelp()65 sys.exit(2)66 for opt, arg in opts:67 if opt == '-h':68 out('Displaying showhelp')69 showhelp()70 sys.exit()71 elif opt == '-o':72 if got_output:73 out('Got more than one output')74 showhelp()75 sys.exit(3)76 got_output = True77 output_name = arg78 elif opt == '-m':79 if module_directory is not None:80 out('Got more than one cache directory')81 showhelp()82 sys.exit(4)83 module_directory = arg84 elif opt == '-M':85 if output_merged is not None:86 out('Got more than one output merged path')87 showhelp()88 sys.exit(5)89 output_merged = arg90 elif opt == '-P':91 assert not got_preprocessed_input92 assert json_dict == {}93 with open(arg, 'rb') as dict_file:94 dictionary = pickle.load(dict_file)95 got_preprocessed_input = True96 cleared_dir = False97 for arg in args:98 got_input = True99 with open(arg) as f:100 srcs = list(yaml.load_all(f.read(), Loader=yaml.FullLoader))101 for src in srcs:102 if isinstance(src, str):103 assert len(srcs) == 1104 template = Template(src,105 filename=arg,106 module_directory=module_directory,107 lookup=TemplateLookup(directories=['.']))108 with open(output_name, 'w') as output_file:109 render_template(template, Context(output_file,110 **dictionary))111 else:112 # we have optional control data: this template represents113 # a directory114 if not cleared_dir:115 if not os.path.exists(output_name):116 pass117 elif os.path.isfile(output_name):118 os.unlink(output_name)119 else:120 shutil.rmtree(output_name, ignore_errors=True)121 cleared_dir = True122 items = []123 if 'foreach' in src:124 for el in dictionary[src['foreach']]:125 if 'cond' in src:126 args = dict(dictionary)127 args['selected'] = el128 if not eval(src['cond'], {}, args):129 continue130 items.append(el)131 assert items132 else:133 items = [None]134 for item in items:135 args = dict(dictionary)136 args['selected'] = item137 item_output_name = os.path.join(138 output_name,139 Template(src['output_name']).render(**args))140 if not os.path.exists(os.path.dirname(item_output_name)):141 os.makedirs(os.path.dirname(item_output_name))142 template = Template(143 src['template'],144 filename=arg,145 module_directory=module_directory,146 lookup=TemplateLookup(directories=['.']))147 with open(item_output_name, 'w') as output_file:148 render_template(template, Context(output_file, **args))149 if not got_input and not preprocessed_output:150 out('Got nothing to do')151 showhelp()152if __name__ == '__main__':...
Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!