Best Python code snippet using yandex-tank
jquery.multifile.js
Source:jquery.multifile.js  
1/*2 ### jQuery Multiple File Upload Plugin v1.48 - 2012-07-19 ###3 * Home: http://www.fyneworks.com/jquery/multiple-file-upload/4 * Code: http://code.google.com/p/jquery-multifile-plugin/5 *6	* Licensed under http://en.wikipedia.org/wiki/MIT_License7 ###8*/9/*# AVOID COLLISIONS #*/10;if(window.jQuery) (function($){11/*# AVOID COLLISIONS #*/12 13	// plugin initialization14	$.fn.MultiFile = function(options){15		if(this.length==0) return this; // quick fail16		17		// Handle API methods18		if(typeof arguments[0]=='string'){19			// Perform API methods on individual elements20			if(this.length>1){21				var args = arguments;22				return this.each(function(){23					$.fn.MultiFile.apply($(this), args);24    });25			};26			// Invoke API method handler27			$.fn.MultiFile[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);28			// Quick exit...29			return this;30		};31		32		// Initialize options for this call33		var options = $.extend(34			{}/* new object */,35			$.fn.MultiFile.options/* default options */,36			options || {} /* just-in-time options */37		);38		39		// Empty Element Fix!!!40		// this code will automatically intercept native form submissions41		// and disable empty file elements42		$('form')43		.not('MultiFile-intercepted')44		.addClass('MultiFile-intercepted')45		.submit($.fn.MultiFile.disableEmpty);46		47		//### http://plugins.jquery.com/node/136348		// utility method to integrate this plugin with others...49		if($.fn.MultiFile.options.autoIntercept){50			$.fn.MultiFile.intercept( $.fn.MultiFile.options.autoIntercept /* array of methods to intercept */ );51			$.fn.MultiFile.options.autoIntercept = null; /* only run this once */52		};53		54		// loop through each matched element55		this56		 .not('.MultiFile-applied')57			.addClass('MultiFile-applied')58		.each(function(){59			//#####################################################################60			// MAIN PLUGIN FUNCTIONALITY - START61			//#####################################################################62			63       // BUG 1251 FIX: http://plugins.jquery.com/project/comments/add/125164       // variable group_count would repeat itself on multiple calls to the plugin.65       // this would cause a conflict with multiple elements66       // changes scope of variable to global so id will be unique over n calls67       window.MultiFile = (window.MultiFile || 0) + 1;68       var group_count = window.MultiFile;69       70       // Copy parent attributes - Thanks to Jonas Wagner71       // we will use this one to create new input elements72       var MultiFile = {e:this, E:$(this), clone:$(this).clone()};73       74       //===75       76       //# USE CONFIGURATION77       if(typeof options=='number') options = {max:options};78       var o = $.extend({},79        $.fn.MultiFile.options,80        options || {},81   					($.metadata? MultiFile.E.metadata(): ($.meta?MultiFile.E.data():null)) || {}, /* metadata options */82								{} /* internals */83       );84       // limit number of files that can be selected?85       if(!(o.max>0) /*IsNull(MultiFile.max)*/){86        o.max = MultiFile.E.attr('maxlength');87       };88							if(!(o.max>0) /*IsNull(MultiFile.max)*/){89								o.max = (String(MultiFile.e.className.match(/\b(max|limit)\-([0-9]+)\b/gi) || ['']).match(/[0-9]+/gi) || [''])[0];90								if(!(o.max>0)) o.max = -1;91								else           o.max = String(o.max).match(/[0-9]+/gi)[0];92							}93       o.max = new Number(o.max);94       // limit extensions?95       o.accept = o.accept || MultiFile.E.attr('accept') || '';96       if(!o.accept){97        o.accept = (MultiFile.e.className.match(/\b(accept\-[\w\|]+)\b/gi)) || '';98        o.accept = new String(o.accept).replace(/^(accept|ext)\-/i,'');99       };100       101       //===102       103       // APPLY CONFIGURATION104							$.extend(MultiFile, o || {});105       MultiFile.STRING = $.extend({},$.fn.MultiFile.options.STRING,MultiFile.STRING);106       107       //===108       109       //#########################################110       // PRIVATE PROPERTIES/METHODS111       $.extend(MultiFile, {112        n: 0, // How many elements are currently selected?113        slaves: [], files: [],114        instanceKey: MultiFile.e.id || 'MultiFile'+String(group_count), // Instance Key?115        generateID: function(z){ return MultiFile.instanceKey + (z>0 ?'_F'+String(z):''); },116        trigger: function(event, element){117         var handler = MultiFile[event], value = $(element).attr('value');118         if(handler){119          var returnValue = handler(element, value, MultiFile);120          if( returnValue!=null ) return returnValue;121         }122         return true;123        }124       });125       126       //===127       128       // Setup dynamic regular expression for extension validation129       // - thanks to John-Paul Bader: http://smyck.de/2006/08/11/javascript-dynamic-regular-expresions/130       if(String(MultiFile.accept).length>1){131								MultiFile.accept = MultiFile.accept.replace(/\W+/g,'|').replace(/^\W|\W$/g,'');132        MultiFile.rxAccept = new RegExp('\\.('+(MultiFile.accept?MultiFile.accept:'')+')$','gi');133       };134       135       //===136       137       // Create wrapper to hold our file list138       MultiFile.wrapID = MultiFile.instanceKey+'_wrap'; // Wrapper ID?139       MultiFile.E.wrap('<div class="MultiFile-wrap" id="'+MultiFile.wrapID+'"></div>');140       MultiFile.wrapper = $('#'+MultiFile.wrapID+'');141       142       //===143       144       // MultiFile MUST have a name - default: file1[], file2[], file3[]145       MultiFile.e.name = MultiFile.e.name || 'file'+ group_count +'[]';146       147       //===148       149							if(!MultiFile.list){150								// Create a wrapper for the list151								// * OPERA BUG: NO_MODIFICATION_ALLOWED_ERR ('list' is a read-only property)152								// this change allows us to keep the files in the order they were selected153								MultiFile.wrapper.append( '<div class="MultiFile-list" id="'+MultiFile.wrapID+'_list"></div>' );154								MultiFile.list = $('#'+MultiFile.wrapID+'_list');155							};156       MultiFile.list = $(MultiFile.list);157							158       //===159       160       // Bind a new element161       MultiFile.addSlave = function( slave, slave_count ){162								//if(window.console) console.log('MultiFile.addSlave',slave_count);163								164        // Keep track of how many elements have been displayed165        MultiFile.n++;166        // Add reference to master element167        slave.MultiFile = MultiFile;168								169								// BUG FIX: http://plugins.jquery.com/node/1495170								// Clear identifying properties from clones171								if(slave_count>0) slave.id = slave.name = '';172								173        // Define element's ID and name (upload components need this!)174        //slave.id = slave.id || MultiFile.generateID(slave_count);175								if(slave_count>0) slave.id = MultiFile.generateID(slave_count);176								//FIX for: http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=23177        178        // 2008-Apr-29: New customizable naming convention (see url below)179        // http://groups.google.com/group/jquery-dev/browse_frm/thread/765c73e41b34f924#180        slave.name = String(MultiFile.namePattern181         /*master name*/.replace(/\$name/gi,$(MultiFile.clone).attr('name'))182         /*master id  */.replace(/\$id/gi,  $(MultiFile.clone).attr('id'))183         /*group count*/.replace(/\$g/gi,   group_count)//(group_count>0?group_count:''))184         /*slave count*/.replace(/\$i/gi,   slave_count)//(slave_count>0?slave_count:''))185        );186        187        // If we've reached maximum number, disable input slave188        if( (MultiFile.max > 0) && ((MultiFile.n-1) > (MultiFile.max)) )//{ // MultiFile.n Starts at 1, so subtract 1 to find true count189         slave.disabled = true;190        //};191        192        // Remember most recent slave193        MultiFile.current = MultiFile.slaves[slave_count] = slave;194        195								// We'll use jQuery from now on196								slave = $(slave);197        198        // Clear value199        slave.val('').attr('value','')[0].value = '';200        201								// Stop plugin initializing on slaves202								slave.addClass('MultiFile-applied');203								204        // Triggered when a file is selected205        slave.change(function(){206          //if(window.console) console.log('MultiFile.slave.change',slave_count);207 								 208          // Lose focus to stop IE7 firing onchange again209          $(this).blur();210          211          //# Trigger Event! onFileSelect212          if(!MultiFile.trigger('onFileSelect', this, MultiFile)) return false;213          //# End Event!214          215          //# Retrive value of selected file from element216          var ERROR = '', v = String(this.value || ''/*.attr('value)*/);217          218          // check extension219          if(MultiFile.accept && v && !v.match(MultiFile.rxAccept))//{220            ERROR = MultiFile.STRING.denied.replace('$ext', String(v.match(/\.\w{1,4}$/gi)));221           //}222          //};223          224          // Disallow duplicates225										for(var f in MultiFile.slaves)//{226           if(MultiFile.slaves[f] && MultiFile.slaves[f]!=this)//{227  										//console.log(MultiFile.slaves[f],MultiFile.slaves[f].value);228            if(MultiFile.slaves[f].value==v)//{229             ERROR = MultiFile.STRING.duplicate.replace('$file', v.match(/[^\/\\]+$/gi));230            //};231           //};232          //};233          234          // Create a new file input element235          var newEle = $(MultiFile.clone).clone();// Copy parent attributes - Thanks to Jonas Wagner236          //# Let's remember which input we've generated so237          // we can disable the empty ones before submission238          // See: http://plugins.jquery.com/node/1495239          newEle.addClass('MultiFile');240          241          // Handle error242          if(ERROR!=''){243            // Handle error244            MultiFile.error(ERROR);245												246            // 2007-06-24: BUG FIX - Thanks to Adrian Wróbel <adrian [dot] wrobel [at] gmail.com>247            // Ditch the trouble maker and add a fresh new element248            MultiFile.n--;249            MultiFile.addSlave(newEle[0], slave_count);250            slave.parent().prepend(newEle);251            slave.remove();252            return false;253          };254          255          // Hide this element (NB: display:none is evil!)256          $(this).css({ position:'absolute', top: '-3000px' });257          258          // Add new element to the form259          slave.after(newEle);260          261          // Update list262          MultiFile.addToList( this, slave_count );263          264          // Bind functionality265          MultiFile.addSlave( newEle[0], slave_count+1 );266          267          //# Trigger Event! afterFileSelect268          if(!MultiFile.trigger('afterFileSelect', this, MultiFile)) return false;269          //# End Event!270          271        }); // slave.change()272								273								// Save control to element274								$(slave).data('MultiFile', MultiFile);275								276       };// MultiFile.addSlave277       // Bind a new element278       279       280       281       // Add a new file to the list282       MultiFile.addToList = function( slave, slave_count ){283        //if(window.console) console.log('MultiFile.addToList',slave_count);284								285        //# Trigger Event! onFileAppend286        if(!MultiFile.trigger('onFileAppend', slave, MultiFile)) return false;287        //# End Event!288        289        // Create label elements290        var291         r = $('<div class="MultiFile-label"></div>'),292         v = String(slave.value || ''/*.attr('value)*/),293         a = $('<span class="MultiFile-title" title="'+MultiFile.STRING.selected.replace('$file', v)+'">'+MultiFile.STRING.file.replace('$file', v.match(/[^\/\\]+$/gi)[0])+'</span>'),294         b = $('<a class="MultiFile-remove" href="#'+MultiFile.wrapID+'">'+MultiFile.STRING.remove+'</a>');295        296        // Insert label297        MultiFile.list.append(298         r.append(b, ' ', a)299        );300        301        b302								.click(function(){303         304          //# Trigger Event! onFileRemove305          if(!MultiFile.trigger('onFileRemove', slave, MultiFile)) return false;306          //# End Event!307          308          MultiFile.n--;309          MultiFile.current.disabled = false;310          311          // Remove element, remove label, point to current312										MultiFile.slaves[slave_count] = null;313										$(slave).remove();314										$(this).parent().remove();315										316          // Show most current element again (move into view) and clear selection317          $(MultiFile.current).css({ position:'', top: '' });318										$(MultiFile.current).reset().val('').attr('value', '')[0].value = '';319          320          //# Trigger Event! afterFileRemove321          if(!MultiFile.trigger('afterFileRemove', slave, MultiFile)) return false;322          //# End Event!323										324          return false;325        });326        327        //# Trigger Event! afterFileAppend328        if(!MultiFile.trigger('afterFileAppend', slave, MultiFile)) return false;329        //# End Event!330        331       }; // MultiFile.addToList332       // Add element to selected files list333       334       335       336       // Bind functionality to the first element337       if(!MultiFile.MultiFile) MultiFile.addSlave(MultiFile.e, 0);338       339       // Increment control count340       //MultiFile.I++; // using window.MultiFile341       MultiFile.n++;342							343							// Save control to element344							MultiFile.E.data('MultiFile', MultiFile);345							346			//#####################################################################347			// MAIN PLUGIN FUNCTIONALITY - END348			//#####################################################################349		}); // each element350	};351	352	/*--------------------------------------------------------*/353	354	/*355		### Core functionality and API ###356	*/357	$.extend($.fn.MultiFile, {358  /**359   * This method removes all selected files360   *361   * Returns a jQuery collection of all affected elements.362   *363   * @name reset364   * @type jQuery365   * @cat Plugins/MultiFile366   * @author Diego A. (http://www.fyneworks.com/)367   *368   * @example $.fn.MultiFile.reset();369   */370  reset: function(){371			var settings = $(this).data('MultiFile');372			//if(settings) settings.wrapper.find('a.MultiFile-remove').click();373			if(settings) settings.list.find('a.MultiFile-remove').click();374   return $(this);375  },376  377  378  /**379   * This utility makes it easy to disable all 'empty' file elements in the document before submitting a form.380   * It marks the affected elements so they can be easily re-enabled after the form submission or validation.381   *382   * Returns a jQuery collection of all affected elements.383   *384   * @name disableEmpty385   * @type jQuery386   * @cat Plugins/MultiFile387   * @author Diego A. (http://www.fyneworks.com/)388   *389   * @example $.fn.MultiFile.disableEmpty();390   * @param String class (optional) A string specifying a class to be applied to all affected elements - Default: 'mfD'.391   */392  disableEmpty: function(klass){ klass = (typeof(klass)=='string'?klass:'')||'mfD';393   var o = [];394   $('input:file.MultiFile').each(function(){ if($(this).val()=='') o[o.length] = this; });395   return $(o).each(function(){ this.disabled = true }).addClass(klass);396  },397  398  399		/**400			* This method re-enables 'empty' file elements that were disabled (and marked) with the $.fn.MultiFile.disableEmpty method.401			*402			* Returns a jQuery collection of all affected elements.403			*404			* @name reEnableEmpty405			* @type jQuery406			* @cat Plugins/MultiFile407			* @author Diego A. (http://www.fyneworks.com/)408			*409			* @example $.fn.MultiFile.reEnableEmpty();410			* @param String klass (optional) A string specifying the class that was used to mark affected elements - Default: 'mfD'.411			*/412  reEnableEmpty: function(klass){ klass = (typeof(klass)=='string'?klass:'')||'mfD';413   return $('input:file.'+klass).removeClass(klass).each(function(){ this.disabled = false });414  },415  416  417		/**418			* This method will intercept other jQuery plugins and disable empty file input elements prior to form submission419			*420	421			* @name intercept422			* @cat Plugins/MultiFile423			* @author Diego A. (http://www.fyneworks.com/)424			*425			* @example $.fn.MultiFile.intercept();426			* @param Array methods (optional) Array of method names to be intercepted427			*/428  intercepted: {},429  intercept: function(methods, context, args){430   var method, value; args = args || [];431   if(args.constructor.toString().indexOf("Array")<0) args = [ args ];432   if(typeof(methods)=='function'){433    $.fn.MultiFile.disableEmpty();434    value = methods.apply(context || window, args);435				//SEE-http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=27436				setTimeout(function(){ $.fn.MultiFile.reEnableEmpty() },1000);437    return value;438   };439   if(methods.constructor.toString().indexOf("Array")<0) methods = [methods];440   for(var i=0;i<methods.length;i++){441    method = methods[i]+''; // make sure that we have a STRING442    if(method) (function(method){ // make sure that method is ISOLATED for the interception443     $.fn.MultiFile.intercepted[method] = $.fn[method] || function(){};444     $.fn[method] = function(){445      $.fn.MultiFile.disableEmpty();446      value = $.fn.MultiFile.intercepted[method].apply(this, arguments);447						//SEE http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=27448      setTimeout(function(){ $.fn.MultiFile.reEnableEmpty() },1000);449      return value;450     }; // interception451    })(method); // MAKE SURE THAT method IS ISOLATED for the interception452   };// for each method453  } // $.fn.MultiFile.intercept454		455 });456	457	/*--------------------------------------------------------*/458	459	/*460		### Default Settings ###461		eg.: You can override default control like this:462		$.fn.MultiFile.options.accept = 'gif|jpg';463	*/464	$.fn.MultiFile.options = { //$.extend($.fn.MultiFile, { options: {465		accept: '', // accepted file extensions466		max: -1,    // maximum number of selectable files467		468		// name to use for newly created elements469		namePattern: '$name', // same name by default (which creates an array)470         /*master name*/ // use $name471         /*master id  */ // use $id472         /*group count*/ // use $g473         /*slave count*/ // use $i474									/*other      */ // use any combination of he above, eg.: $name_file$i475		476		// STRING: collection lets you show messages in different languages477		STRING: {478			remove:'x',479			denied:'You cannot select a $ext file.\nTry again...',480			file:'$file',481			selected:'File selected: $file',482			duplicate:'This file has already been selected:\n$file'483		},484		485		// name of methods that should be automcatically intercepted so the plugin can disable486		// extra file elements that are empty before execution and automatically re-enable them afterwards487  autoIntercept: [ 'submit', 'ajaxSubmit', 'ajaxForm', 'validate', 'valid' /* array of methods to intercept */ ],488		489		// error handling function490		error: function(s){491			/*492			ERROR! blockUI is not currently working in IE493			if($.blockUI){494				$.blockUI({495					message: s.replace(/\n/gi,'<br/>'),496					css: { 497						border:'none', padding:'15px', size:'12.0pt',498						backgroundColor:'#900', color:'#fff',499						opacity:'.8','-webkit-border-radius': '10px','-moz-border-radius': '10px'500					}501				});502				window.setTimeout($.unblockUI, 2000);503			}504			else//{// save a byte!505			*/506			 alert(s);507			//}// save a byte!508		}509 }; //} });510	511	/*--------------------------------------------------------*/512	513	/*514		### Additional Methods ###515		Required functionality outside the plugin's scope516	*/517	518	// Native input reset method - because this alone doesn't always work: $(element).val('').attr('value', '')[0].value = '';519	$.fn.reset = function(){ return this.each(function(){ try{ this.reset(); }catch(e){} }); };520	521	/*--------------------------------------------------------*/522	523	/*524		### Default implementation ###525		The plugin will attach itself to file inputs526		with the class 'multi' when the page loads527	*/528	$(function(){529  //$("input:file.multi").MultiFile();530  $("input[type=file].multi").MultiFile();531 });532	533	534	535/*# AVOID COLLISIONS #*/536})(jQuery);...TestContainerCommands.py
Source:TestContainerCommands.py  
1"""2Test user added container commands3"""4import sys5import lldb6from lldbsuite.test.decorators import *7from lldbsuite.test.lldbtest import *8class TestCmdContainer(TestBase):9    NO_DEBUG_INFO_TESTCASE = True10    def test_container_add(self):11        self.container_add()12    def check_command_tree_exists(self):13        """This makes sure we can still run the command tree we added."""14        self.runCmd("test-multi")15        self.runCmd("test-multi test-multi-sub")16        self.runCmd("test-multi test-multi-sub welcome")17        18    def container_add(self):19        # Make sure we can't overwrite built-in commands:20        self.expect("command container add process", "Can't replace builtin container command",21                    substrs=["can't replace builtin command"], error=True)22        self.expect("command container add process non_such_subcommand", "Can't add to built-in subcommand", 23                    substrs=["Path component: 'process' is not a user command"], error=True)24        self.expect("command container add process launch", "Can't replace builtin subcommand", 25                    substrs=["Path component: 'process' is not a user command"], error=True)26        # Now lets make a container command:27        self.runCmd("command container add -h 'A test container command' test-multi")28        # Make sure the help works:29        self.expect("help test-multi", "Help works for top-level multi",30                    substrs=["A test container command"])31        # Add a subcommand:32        self.runCmd("command container add -h 'A test container sub-command' test-multi test-multi-sub")33        # Make sure the help works:34        self.expect("help test-multi", "Help shows sub-multi",35                    substrs=["A test container command", "test-multi-sub -- A test container sub-command"])36        self.expect("help test-multi test-multi-sub", "Help shows sub-multi",37                    substrs=["A test container sub-command"])38        # Now add a script based command to the container command:39        self.runCmd("command script import welcome.py")40        self.runCmd("command script add -c welcome.WelcomeCommand test-multi test-multi-sub welcome")41        # Make sure the help still works:42        self.expect("help test-multi test-multi-sub", "Listing subcommands works",43                    substrs=["A test container sub-command", "welcome -- Just a docstring for Welcome"])44        self.expect("help test-multi test-multi-sub welcome", "Subcommand help works",45                    substrs=["Just a docstring for Welcome"])46        # And make sure it actually works:47        self.expect("test-multi test-multi-sub welcome friend", "Test command works",48                    substrs=["Hello friend, welcome to LLDB"])49        # Make sure overwriting works on the leaf command.  First using the50        # explicit option so we should not be able to remove extant commands by default:51        self.expect("command script add -c welcome.WelcomeCommand2 test-multi test-multi-sub welcome",52                    "overwrite command w/o -o",53                    substrs=["cannot add command: sub-command already exists"], error=True)54        # But we can with the -o option:55        self.runCmd("command script add -c welcome.WelcomeCommand2 -o test-multi test-multi-sub welcome")56        # Make sure we really did overwrite:57        self.expect("test-multi test-multi-sub welcome friend", "Used the new command class",58                    substrs=["Hello friend, welcome again to LLDB"])59        self.expect("apropos welcome", "welcome should show up in apropos", substrs=["A docstring for the second Welcome"])60        self.expect("help test-multi test-multi-sub welcome", "welcome should show up in help", substrs=["A docstring for the second Welcome"])61        self.expect("help", "test-multi should show up in help", substrs=["test-multi"])62                    63        # Now switch the default and make sure we can now delete w/o the overwrite option:64        self.runCmd("settings set interpreter.require-overwrite 0")65        self.runCmd("command script add -c welcome.WelcomeCommand test-multi test-multi-sub welcome")66        # Make sure we really did overwrite:67        self.expect("test-multi test-multi-sub welcome friend", "Used the new command class",68                    substrs=["Hello friend, welcome to LLDB"])69        70        # Make sure we give good errors when the input is wrong:71        self.expect("command script delete test-mult test-multi-sub welcome", "Delete script command - wrong first path component",72                    substrs=["'test-mult' not found"], error=True)73        74        self.expect("command script delete test-multi test-multi-su welcome", "Delete script command - wrong second path component",75                    substrs=["'test-multi-su' not found"], error=True)76        self.check_command_tree_exists()77        78        self.expect("command script delete test-multi test-multi-sub welcom", "Delete script command - wrong leaf component",79                    substrs=["'welcom' not found"], error=True)80        self.check_command_tree_exists()81        82        self.expect("command script delete test-multi test-multi-sub", "Delete script command - no leaf component",83                    substrs=["subcommand 'test-multi-sub' is not a user command"], error=True)84        self.check_command_tree_exists()85        # You can't use command script delete to delete container commands:86        self.expect("command script delete test-multi", "Delete script - can't delete container",87                    substrs=["command 'test-multi' is a multi-word command."], error=True)88        self.expect("command script delete test-multi test-multi-sub", "Delete script - can't delete container",89                    substrs=["subcommand 'test-multi-sub' is not a user command"], error = True)90        # You can't use command container delete to delete scripted commands:91        self.expect("command container delete test-multi test-multi-sub welcome", "command container can't delete user commands",92                    substrs=["subcommand 'welcome' is not a container command"], error = True)93        94        # Also make sure you can't alias on top of container commands:95        self.expect("command alias test-multi process launch", "Tried to alias on top of a container command",96                    substrs=["'test-multi' is a user container command and cannot be overwritten."], error=True)97        self.check_command_tree_exists()98        # Also assert that we can't delete builtin commands:99        self.expect("command script delete process launch", "Delete builtin command fails", substrs=["command 'process' is not a user command"], error=True)100        # Now let's do the version that works101        self.expect("command script delete test-multi test-multi-sub welcome", "Delete script command by path", substrs=["Deleted command: test-multi test-multi-sub welcome"])102        # Now overwrite the sub-command, it should end up empty:103        self.runCmd("command container add -h 'A different help string' -o test-multi test-multi-sub")104        # welcome should be gone:105        self.expect("test-multi test-multi-sub welcome friend", "did remove subcommand",106                    substrs=["'test-multi-sub' does not have any subcommands."], error=True)107        # We should have the new help:108        self.expect("help test-multi test-multi-sub", "help changed",109                    substrs=["A different help string"])110        # Now try deleting commands.111        self.runCmd("command container delete test-multi test-multi-sub")112        self.expect("test-multi test-multi-sub", "Command is not active", error=True,113                    substrs = ["'test-multi' does not have any subcommands"])114        self.expect("help test-multi", matching=False, substrs=["test-multi-sub"])115                    116        # Next the root command:117        self.runCmd("command container delete test-multi")...createMultiSort.jest.js
Source:createMultiSort.jest.js  
1import createMultiSort from './createMultiSort';2describe('createMultiSort', () => {3  function simulate(4    sort,5    dataKey,6    eventModifier = '',7    defaultSortDirection = 'ASC',8  ) {9    sort({10      defaultSortDirection,11      event: {12        ctrlKey: eventModifier === 'control',13        metaKey: eventModifier === 'meta',14        shiftKey: eventModifier === 'shift',15      },16      sortBy: dataKey,17    });18  }19  it('errors if the user did not specify a sort callback', () => {20    expect(createMultiSort).toThrow();21  });22  it('sets the correct default values', () => {23    const multiSort = createMultiSort(jest.fn(), {24      defaultSortBy: ['a', 'b'],25      defaultSortDirection: {26        a: 'ASC',27        b: 'DESC',28      },29    });30    expect(multiSort.sortBy).toEqual(['a', 'b']);31    expect(multiSort.sortDirection.a).toBe('ASC');32    expect(multiSort.sortDirection.b).toBe('DESC');33  });34  it('sets the correct default sparse values', () => {35    const multiSort = createMultiSort(jest.fn(), {36      defaultSortBy: ['a', 'b'],37    });38    expect(multiSort.sortBy).toEqual(['a', 'b']);39    expect(multiSort.sortDirection.a).toBe('ASC');40    expect(multiSort.sortDirection.b).toBe('ASC');41  });42  describe('on click', () => {43    it('sets the correct default value for a field', () => {44      const multiSort = createMultiSort(jest.fn());45      simulate(multiSort.sort, 'a');46      expect(multiSort.sortBy).toEqual(['a']);47      expect(multiSort.sortDirection.a).toBe('ASC');48      simulate(multiSort.sort, 'b', '', 'DESC');49      expect(multiSort.sortBy).toEqual(['b']);50      expect(multiSort.sortDirection.b).toBe('DESC');51    });52    it('toggles a field value', () => {53      const multiSort = createMultiSort(jest.fn());54      simulate(multiSort.sort, 'a');55      expect(multiSort.sortBy).toEqual(['a']);56      expect(multiSort.sortDirection.a).toBe('ASC');57      simulate(multiSort.sort, 'a');58      expect(multiSort.sortBy).toEqual(['a']);59      expect(multiSort.sortDirection.a).toBe('DESC');60      simulate(multiSort.sort, 'b', '', 'DESC');61      expect(multiSort.sortBy).toEqual(['b']);62      expect(multiSort.sortDirection.b).toBe('DESC');63      simulate(multiSort.sort, 'b', '', 'DESC');64      expect(multiSort.sortBy).toEqual(['b']);65      expect(multiSort.sortDirection.b).toBe('ASC');66    });67    it('resets sort-by fields', () => {68      const multiSort = createMultiSort(jest.fn(), {69        defaultSortBy: ['a', 'b'],70      });71      expect(multiSort.sortBy).toEqual(['a', 'b']);72      simulate(multiSort.sort, 'a');73      expect(multiSort.sortBy).toEqual(['a']);74    });75    it('resets sort-direction fields', () => {76      const multiSort = createMultiSort(jest.fn(), {77        defaultSortBy: ['a', 'b'],78        defaultSortDirection: {79          a: 'DESC',80          b: 'ASC',81        },82      });83      expect(multiSort.sortBy).toEqual(['a', 'b']);84      expect(multiSort.sortDirection.a).toEqual('DESC');85      expect(multiSort.sortDirection.b).toEqual('ASC');86      simulate(multiSort.sort, 'a');87      expect(multiSort.sortBy).toEqual(['a']);88      expect(multiSort.sortDirection.a).toEqual('ASC');89      expect(multiSort.sortDirection.b).toEqual(undefined);90      simulate(multiSort.sort, 'b');91      expect(multiSort.sortBy).toEqual(['b']);92      expect(multiSort.sortDirection.a).toEqual(undefined);93      expect(multiSort.sortDirection.b).toEqual('ASC');94    });95  });96  describe('on shift click', () => {97    it('appends a field to the sort by list', () => {98      const multiSort = createMultiSort(jest.fn());99      simulate(multiSort.sort, 'a');100      expect(multiSort.sortBy).toEqual(['a']);101      expect(multiSort.sortDirection.a).toBe('ASC');102      simulate(multiSort.sort, 'b', 'shift');103      expect(multiSort.sortBy).toEqual(['a', 'b']);104      expect(multiSort.sortDirection.a).toBe('ASC');105      expect(multiSort.sortDirection.b).toBe('ASC');106    });107    it('toggles an appended field value', () => {108      const multiSort = createMultiSort(jest.fn());109      simulate(multiSort.sort, 'a');110      expect(multiSort.sortBy).toEqual(['a']);111      expect(multiSort.sortDirection.a).toBe('ASC');112      simulate(multiSort.sort, 'b', 'shift');113      expect(multiSort.sortBy).toEqual(['a', 'b']);114      expect(multiSort.sortDirection.a).toBe('ASC');115      expect(multiSort.sortDirection.b).toBe('ASC');116      simulate(multiSort.sort, 'a', 'shift');117      expect(multiSort.sortBy).toEqual(['a', 'b']);118      expect(multiSort.sortDirection.a).toBe('DESC');119      expect(multiSort.sortDirection.b).toBe('ASC');120      simulate(multiSort.sort, 'a', 'shift');121      expect(multiSort.sortBy).toEqual(['a', 'b']);122      expect(multiSort.sortDirection.a).toBe('ASC');123      expect(multiSort.sortDirection.b).toBe('ASC');124    });125    it('able to shift+click more than once', () => {126      const multiSort = createMultiSort(jest.fn());127      simulate(multiSort.sort, 'a');128      expect(multiSort.sortBy).toEqual(['a']);129      expect(multiSort.sortDirection.a).toBe('ASC');130      simulate(multiSort.sort, 'b', 'shift');131      expect(multiSort.sortBy).toEqual(['a', 'b']);132      expect(multiSort.sortDirection.a).toBe('ASC');133      expect(multiSort.sortDirection.b).toBe('ASC');134      simulate(multiSort.sort, 'b');135      expect(multiSort.sortBy).toEqual(['b']);136      expect(multiSort.sortDirection.b).toBe('DESC');137      simulate(multiSort.sort, 'a', 'shift');138      expect(multiSort.sortBy).toEqual(['b', 'a']);139      expect(multiSort.sortDirection.a).toBe('ASC');140      expect(multiSort.sortDirection.b).toBe('DESC');141    });142  });143  ['control', 'meta'].forEach(modifier => {144    describe(`${modifier} click`, () => {145      it('removes a field from the sort by list', () => {146        const multiSort = createMultiSort(jest.fn(), {147          defaultSortBy: ['a', 'b'],148        });149        expect(multiSort.sortBy).toEqual(['a', 'b']);150        simulate(multiSort.sort, 'a', modifier);151        expect(multiSort.sortBy).toEqual(['b']);152        simulate(multiSort.sort, 'b', modifier);153        expect(multiSort.sortBy).toEqual([]);154      });155      it('ignores fields not in the list on control click', () => {156        const multiSort = createMultiSort(jest.fn(), {157          defaultSortBy: ['a', 'b'],158        });159        expect(multiSort.sortBy).toEqual(['a', 'b']);160        simulate(multiSort.sort, 'c', modifier);161        expect(multiSort.sortBy).toEqual(['a', 'b']);162      });163    });164  });...test_dict.py
Source:test_dict.py  
1"""2Tests for dict duplicate keys Pyflakes behavior.3"""4from sys import version_info5from pyflakes import messages as m6from pyflakes.test.harness import TestCase, skipIf7class Test(TestCase):8    def test_duplicate_keys(self):9        self.flakes(10            "{'yes': 1, 'yes': 2}",11            m.MultiValueRepeatedKeyLiteral,12            m.MultiValueRepeatedKeyLiteral,13        )14    @skipIf(version_info < (3,),15            "bytes and strings with same 'value' are not equal in python3")16    def test_duplicate_keys_bytes_vs_unicode_py3(self):17        self.flakes("{b'a': 1, u'a': 2}")18    @skipIf(version_info < (3,),19            "bytes and strings with same 'value' are not equal in python3")20    def test_duplicate_values_bytes_vs_unicode_py3(self):21        self.flakes(22            "{1: b'a', 1: u'a'}",23            m.MultiValueRepeatedKeyLiteral,24            m.MultiValueRepeatedKeyLiteral,25        )26    @skipIf(version_info >= (3,),27            "bytes and strings with same 'value' are equal in python2")28    def test_duplicate_keys_bytes_vs_unicode_py2(self):29        self.flakes(30            "{b'a': 1, u'a': 2}",31            m.MultiValueRepeatedKeyLiteral,32            m.MultiValueRepeatedKeyLiteral,33        )34    @skipIf(version_info >= (3,),35            "bytes and strings with same 'value' are equal in python2")36    def test_duplicate_values_bytes_vs_unicode_py2(self):37        self.flakes("{1: b'a', 1: u'a'}")38    def test_multiple_duplicate_keys(self):39        self.flakes(40            "{'yes': 1, 'yes': 2, 'no': 2, 'no': 3}",41            m.MultiValueRepeatedKeyLiteral,42            m.MultiValueRepeatedKeyLiteral,43            m.MultiValueRepeatedKeyLiteral,44            m.MultiValueRepeatedKeyLiteral,45        )46    def test_duplicate_keys_in_function(self):47        self.flakes(48            '''49            def f(thing):50                pass51            f({'yes': 1, 'yes': 2})52            ''',53            m.MultiValueRepeatedKeyLiteral,54            m.MultiValueRepeatedKeyLiteral,55        )56    def test_duplicate_keys_in_lambda(self):57        self.flakes(58            "lambda x: {(0,1): 1, (0,1): 2}",59            m.MultiValueRepeatedKeyLiteral,60            m.MultiValueRepeatedKeyLiteral,61        )62    def test_duplicate_keys_tuples(self):63        self.flakes(64            "{(0,1): 1, (0,1): 2}",65            m.MultiValueRepeatedKeyLiteral,66            m.MultiValueRepeatedKeyLiteral,67        )68    def test_duplicate_keys_tuples_int_and_float(self):69        self.flakes(70            "{(0,1): 1, (0,1.0): 2}",71            m.MultiValueRepeatedKeyLiteral,72            m.MultiValueRepeatedKeyLiteral,73        )74    def test_duplicate_keys_ints(self):75        self.flakes(76            "{1: 1, 1: 2}",77            m.MultiValueRepeatedKeyLiteral,78            m.MultiValueRepeatedKeyLiteral,79        )80    def test_duplicate_keys_bools(self):81        self.flakes(82            "{True: 1, True: 2}",83            m.MultiValueRepeatedKeyLiteral,84            m.MultiValueRepeatedKeyLiteral,85        )86    def test_duplicate_keys_bools_false(self):87        # Needed to ensure 2.x correctly coerces these from variables88        self.flakes(89            "{False: 1, False: 2}",90            m.MultiValueRepeatedKeyLiteral,91            m.MultiValueRepeatedKeyLiteral,92        )93    def test_duplicate_keys_none(self):94        self.flakes(95            "{None: 1, None: 2}",96            m.MultiValueRepeatedKeyLiteral,97            m.MultiValueRepeatedKeyLiteral,98        )99    def test_duplicate_variable_keys(self):100        self.flakes(101            '''102            a = 1103            {a: 1, a: 2}104            ''',105            m.MultiValueRepeatedKeyVariable,106            m.MultiValueRepeatedKeyVariable,107        )108    def test_duplicate_variable_values(self):109        self.flakes(110            '''111            a = 1112            b = 2113            {1: a, 1: b}114            ''',115            m.MultiValueRepeatedKeyLiteral,116            m.MultiValueRepeatedKeyLiteral,117        )118    def test_duplicate_variable_values_same_value(self):119        # Current behaviour is not to look up variable values. This is to120        # confirm that.121        self.flakes(122            '''123            a = 1124            b = 1125            {1: a, 1: b}126            ''',127            m.MultiValueRepeatedKeyLiteral,128            m.MultiValueRepeatedKeyLiteral,129        )130    def test_duplicate_key_float_and_int(self):131        """132        These do look like different values, but when it comes to their use as133        keys, they compare as equal and so are actually duplicates.134        The literal dict {1: 1, 1.0: 1} actually becomes {1.0: 1}.135        """136        self.flakes(137            '''138            {1: 1, 1.0: 2}139            ''',140            m.MultiValueRepeatedKeyLiteral,141            m.MultiValueRepeatedKeyLiteral,142        )143    def test_no_duplicate_key_error_same_value(self):144        self.flakes('''145        {'yes': 1, 'yes': 1}146        ''')147    def test_no_duplicate_key_errors(self):148        self.flakes('''149        {'yes': 1, 'no': 2}150        ''')151    def test_no_duplicate_keys_tuples_same_first_element(self):152        self.flakes("{(0,1): 1, (0,2): 1}")153    def test_no_duplicate_key_errors_func_call(self):154        self.flakes('''155        def test(thing):156            pass157        test({True: 1, None: 2, False: 1})158        ''')159    def test_no_duplicate_key_errors_bool_or_none(self):160        self.flakes("{True: 1, None: 2, False: 1}")161    def test_no_duplicate_key_errors_ints(self):162        self.flakes('''163        {1: 1, 2: 1}164        ''')165    def test_no_duplicate_key_errors_vars(self):166        self.flakes('''167        test = 'yes'168        rest = 'yes'169        {test: 1, rest: 2}170        ''')171    def test_no_duplicate_key_errors_tuples(self):172        self.flakes('''173        {(0,1): 1, (0,2): 1}174        ''')175    def test_no_duplicate_key_errors_instance_attributes(self):176        self.flakes('''177        class Test():178            pass179        f = Test()180        f.a = 1181        {f.a: 1, f.a: 1}...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!!
