Best Quick code snippet using Example
SudokuPuzzles.swift
Source:SudokuPuzzles.swift  
...2684    [1,8,4, 7,6,3, 2,5,9]2685    ]2686    /**2687    * Gets Sudoku example for the Sudoku Store.2688    * @param exampleNumber     Example number.2689    * @return                  Sudoku example is exists, otherwise null.2690    * @see SudokuPuzzles#NUMBER_OF_PUZZLE_EXAMPLES2691    */2692    static func getPuzzleExample(exampleNumber: Int) -> [[Int]]{2693    switch exampleNumber {2694    case   0: return PUZZLE_EXAMPLE_000;2695    case   1: return PUZZLE_EXAMPLE_001;2696    case   2: return PUZZLE_EXAMPLE_002;2697    case   3: return PUZZLE_EXAMPLE_003;2698    case   4: return PUZZLE_EXAMPLE_004;2699    case   5: return PUZZLE_EXAMPLE_005;2700    case   6: return PUZZLE_EXAMPLE_006;2701    case   7: return PUZZLE_EXAMPLE_007;2702    case   8: return PUZZLE_EXAMPLE_008;2703    case   9: return PUZZLE_EXAMPLE_009;2704    case  10: return PUZZLE_EXAMPLE_010;2705    case  11: return PUZZLE_EXAMPLE_011;2706    case  12: return PUZZLE_EXAMPLE_012;2707    case  13: return PUZZLE_EXAMPLE_013;2708    case  14: return PUZZLE_EXAMPLE_014;2709    case  15: return PUZZLE_EXAMPLE_015;2710    case  16: return PUZZLE_EXAMPLE_016;2711    case  17: return PUZZLE_EXAMPLE_017;2712    case  18: return PUZZLE_EXAMPLE_018;2713    case  19: return PUZZLE_EXAMPLE_019;2714    case  20: return PUZZLE_EXAMPLE_020;2715    case  21: return PUZZLE_EXAMPLE_021;2716    case  22: return PUZZLE_EXAMPLE_022;2717    case  23: return PUZZLE_EXAMPLE_023;2718    case  24: return PUZZLE_EXAMPLE_024;2719    case  25: return PUZZLE_EXAMPLE_025;2720    case  26: return PUZZLE_EXAMPLE_026;2721    case  27: return PUZZLE_EXAMPLE_027;2722    case  28: return PUZZLE_EXAMPLE_028;2723    case  29: return PUZZLE_EXAMPLE_029;2724    case  30: return PUZZLE_EXAMPLE_030;2725    case  31: return PUZZLE_EXAMPLE_031;2726    case  32: return PUZZLE_EXAMPLE_032;2727    case  33: return PUZZLE_EXAMPLE_033;2728    case  34: return PUZZLE_EXAMPLE_034;2729    case  35: return PUZZLE_EXAMPLE_035;2730    case  36: return PUZZLE_EXAMPLE_036;2731    case  37: return PUZZLE_EXAMPLE_037;2732    case  38: return PUZZLE_EXAMPLE_038;2733    case  39: return PUZZLE_EXAMPLE_039;2734    case  40: return PUZZLE_EXAMPLE_040;2735    case  41: return PUZZLE_EXAMPLE_041;2736    case  42: return PUZZLE_EXAMPLE_042;2737    case  43: return PUZZLE_EXAMPLE_043;2738    case  44: return PUZZLE_EXAMPLE_044;2739    case  45: return PUZZLE_EXAMPLE_045;2740    case  46: return PUZZLE_EXAMPLE_046;2741    case  47: return PUZZLE_EXAMPLE_047;2742    case  48: return PUZZLE_EXAMPLE_048;2743    case  49: return PUZZLE_EXAMPLE_049;2744    case  50: return PUZZLE_EXAMPLE_050;2745    case  51: return PUZZLE_EXAMPLE_051;2746    case  52: return PUZZLE_EXAMPLE_052;2747    case  53: return PUZZLE_EXAMPLE_053;2748    case  54: return PUZZLE_EXAMPLE_054;2749    case  55: return PUZZLE_EXAMPLE_055;2750    case  56: return PUZZLE_EXAMPLE_056;2751    case  57: return PUZZLE_EXAMPLE_057;2752    case  58: return PUZZLE_EXAMPLE_058;2753    case  59: return PUZZLE_EXAMPLE_059;2754    case  60: return PUZZLE_EXAMPLE_060;2755    case  61: return PUZZLE_EXAMPLE_061;2756    case  62: return PUZZLE_EXAMPLE_062;2757    case  63: return PUZZLE_EXAMPLE_063;2758    case  64: return PUZZLE_EXAMPLE_064;2759    case  65: return PUZZLE_EXAMPLE_065;2760    case  66: return PUZZLE_EXAMPLE_066;2761    case  67: return PUZZLE_EXAMPLE_067;2762    case  68: return PUZZLE_EXAMPLE_068;2763    case  69: return PUZZLE_EXAMPLE_069;2764    case  70: return PUZZLE_EXAMPLE_070;2765    case  71: return PUZZLE_EXAMPLE_071;2766    case  72: return PUZZLE_EXAMPLE_072;2767    case  73: return PUZZLE_EXAMPLE_073;2768    case  74: return PUZZLE_EXAMPLE_074;2769    case  75: return PUZZLE_EXAMPLE_075;2770    case  76: return PUZZLE_EXAMPLE_076;2771    case  77: return PUZZLE_EXAMPLE_077;2772    case  78: return PUZZLE_EXAMPLE_078;2773    case  79: return PUZZLE_EXAMPLE_079;2774    case  80: return PUZZLE_EXAMPLE_080;2775    case  81: return PUZZLE_EXAMPLE_081;2776    case  82: return PUZZLE_EXAMPLE_082;2777    case  83: return PUZZLE_EXAMPLE_083;2778    case  84: return PUZZLE_EXAMPLE_084;2779    case  85: return PUZZLE_EXAMPLE_085;2780    case  86: return PUZZLE_EXAMPLE_086;2781    case  87: return PUZZLE_EXAMPLE_087;2782    case  88: return PUZZLE_EXAMPLE_088;2783    case  89: return PUZZLE_EXAMPLE_089;2784    case  90: return PUZZLE_EXAMPLE_090;2785    case  91: return PUZZLE_EXAMPLE_091;2786    case  92: return PUZZLE_EXAMPLE_092;2787    case  93: return PUZZLE_EXAMPLE_093;2788    case  94: return PUZZLE_EXAMPLE_094;2789    case  95: return PUZZLE_EXAMPLE_095;2790    case  96: return PUZZLE_EXAMPLE_096;2791    case  97: return PUZZLE_EXAMPLE_097;2792    case  98: return PUZZLE_EXAMPLE_098;2793    case  99: return PUZZLE_EXAMPLE_099;2794    case 100: return PUZZLE_EXAMPLE_100;2795    case 101: return PUZZLE_EXAMPLE_101;2796    case 102: return PUZZLE_EXAMPLE_102;2797    case 103: return PUZZLE_EXAMPLE_103;2798    case 104: return PUZZLE_EXAMPLE_104;2799    case 105: return PUZZLE_EXAMPLE_105;2800    case 106: return PUZZLE_EXAMPLE_106;2801    case 107: return PUZZLE_EXAMPLE_107;2802    case 108: return PUZZLE_EXAMPLE_108;2803    case 109: return PUZZLE_EXAMPLE_109;2804    case 110: return PUZZLE_EXAMPLE_110;2805    case 111: return PUZZLE_EXAMPLE_111;2806    case 112: return PUZZLE_EXAMPLE_112;2807    case 113: return PUZZLE_EXAMPLE_113;2808    case 114: return PUZZLE_EXAMPLE_114;2809    case 115: return PUZZLE_EXAMPLE_115;2810    case 116: return PUZZLE_EXAMPLE_116;2811    case 117: return PUZZLE_EXAMPLE_117;2812    case 118: return PUZZLE_EXAMPLE_118;2813    case 119: return PUZZLE_EXAMPLE_119;2814    case 120: return PUZZLE_EXAMPLE_120;2815    case 121: return PUZZLE_EXAMPLE_121;2816    case 122: return PUZZLE_EXAMPLE_122;2817    case 123: return PUZZLE_EXAMPLE_123;2818    case 124: return PUZZLE_EXAMPLE_124;2819    case 125: return PUZZLE_EXAMPLE_125;2820    case 126: return PUZZLE_EXAMPLE_126;2821    case 127: return PUZZLE_EXAMPLE_127;2822    case 128: return PUZZLE_EXAMPLE_128;2823    case 129: return PUZZLE_EXAMPLE_129;2824    case 130: return PUZZLE_EXAMPLE_130;2825    case 131: return PUZZLE_EXAMPLE_131;2826    case 132: return PUZZLE_EXAMPLE_132;2827    case 133: return PUZZLE_EXAMPLE_133;2828    case 134: return PUZZLE_EXAMPLE_134;2829    case 135: return PUZZLE_EXAMPLE_135;2830    case 136: return PUZZLE_EXAMPLE_136;2831    case 137: return PUZZLE_EXAMPLE_137;2832    case 138: return PUZZLE_EXAMPLE_138;2833    case 139: return PUZZLE_EXAMPLE_139;2834    case 140: return PUZZLE_EXAMPLE_140;2835    case 141: return PUZZLE_EXAMPLE_141;2836    case 142: return PUZZLE_EXAMPLE_142;2837    case 143: return PUZZLE_EXAMPLE_143;2838    case 144: return PUZZLE_EXAMPLE_144;2839    case 145: return PUZZLE_EXAMPLE_145;2840    case 146: return PUZZLE_EXAMPLE_146;2841    case 147: return PUZZLE_EXAMPLE_147;2842    case 148: return PUZZLE_EXAMPLE_148;2843    case 149: return PUZZLE_EXAMPLE_149;2844    case 150: return PUZZLE_EXAMPLE_150;2845    case 151: return PUZZLE_EXAMPLE_151;2846    case 152: return PUZZLE_EXAMPLE_152;2847    case 153: return PUZZLE_EXAMPLE_153;2848    case 154: return PUZZLE_EXAMPLE_154;2849    case 155: return PUZZLE_EXAMPLE_155;2850    case 156: return PUZZLE_EXAMPLE_156;2851    case 157: return PUZZLE_EXAMPLE_157;2852    case 158: return PUZZLE_EXAMPLE_158;2853    case 159: return PUZZLE_EXAMPLE_159;2854    case 160: return PUZZLE_EXAMPLE_160;2855    default: return PUZZLE_EMPTY2856    }2857    //return PUZZLE_EMPTY2858    }2859    /**2860    * Returns pre-calculated puzzle example difficulty rating based on2861    * the average number of steps-back performed while recursive2862    * solving sudoku board.2863    *2864    * @param exampleNumber    The example number {@link SudokuPuzzles#NUMBER_OF_PUZZLE_EXAMPLES}2865    * @return Puzzle example difficulty rating if example exist, otherwise -1.2866    */2867    static func getPuzzleExampleRating(exampleNumber: Int) -> Double {2868    switch exampleNumber {2869    case 0: return 16508.0;2870    case 1: return 0.4883;2871    case 2: return 51.2331;2872    case 3: return 55.591;2873    case 4: return 0.3388;2874    case 5: return 56.0881;2875    case 6: return 96.6181;2876    case 7: return 33.6664;2877    case 8: return 0.0;2878    case 9: return 353.9754;2879    case 10: return 109.1;2880    case 11: return 0.0;2881    case 12: return 165.0856;...autolink_test.go
Source:autolink_test.go  
1// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.2// See License.txt for license information.3package markdown4import (5	"testing"6	"github.com/stretchr/testify/assert"7)8func TestParseURLAutolink(t *testing.T) {9	testCases := []struct {10		Description string11		Input       string12		Position    int13		Expected    string14	}{15		{16			Description: "no link",17			Input:       "This is an :emoji:",18			Position:    11,19			Expected:    "",20		},21		{22			Description: "no link 2",23			Input:       "These are two things: apple and orange",24			Position:    20,25			Expected:    "",26		},27		{28			Description: "link with http",29			Input:       "http://example.com and some text",30			Position:    4,31			Expected:    "http://example.com",32		},33		{34			Description: "link with https",35			Input:       "https://example.com and some text",36			Position:    5,37			Expected:    "https://example.com",38		},39		{40			Description: "link with ftp",41			Input:       "ftp://example.com and some text",42			Position:    3,43			Expected:    "ftp://example.com",44		},45		{46			Description: "link with a path",47			Input:       "https://example.com/abcd and some text",48			Position:    5,49			Expected:    "https://example.com/abcd",50		},51		{52			Description: "link with parameters",53			Input:       "ftp://example.com/abcd?foo=bar and some text",54			Position:    3,55			Expected:    "ftp://example.com/abcd?foo=bar",56		},57		{58			Description: "link, not at start",59			Input:       "This is https://example.com and some text",60			Position:    13,61			Expected:    "https://example.com",62		},63		{64			Description: "link with a path, not at start",65			Input:       "This is also http://www.example.com/abcd and some text",66			Position:    17,67			Expected:    "http://www.example.com/abcd",68		},69		{70			Description: "link with parameters, not at start",71			Input:       "These are https://www.example.com/abcd?foo=bar and some text",72			Position:    15,73			Expected:    "https://www.example.com/abcd?foo=bar",74		},75		{76			Description: "link with trailing characters",77			Input:       "This is ftp://www.example.com??",78			Position:    11,79			Expected:    "ftp://www.example.com",80		},81		{82			Description: "multiple links",83			Input:       "This is https://example.com/abcd and ftp://www.example.com/1234",84			Position:    13,85			Expected:    "https://example.com/abcd",86		},87		{88			Description: "second of multiple links",89			Input:       "This is https://example.com/abcd and ftp://www.example.com/1234",90			Position:    40,91			Expected:    "ftp://www.example.com/1234",92		},93		{94			Description: "link with brackets",95			Input:       "Go to ftp://www.example.com/my/page_(disambiguation) and some text",96			Position:    9,97			Expected:    "ftp://www.example.com/my/page_(disambiguation)",98		},99		{100			Description: "link in brackets",101			Input:       "(https://www.example.com/foo/bar)",102			Position:    6,103			Expected:    "https://www.example.com/foo/bar",104		},105		{106			Description: "link in underscores",107			Input:       "_http://www.example.com_",108			Position:    5,109			Expected:    "http://www.example.com",110		},111		{112			Description: "link in asterisks",113			Input:       "This is **ftp://example.com**",114			Position:    13,115			Expected:    "ftp://example.com",116		},117		{118			Description: "link in strikethrough",119			Input:       "Those were ~~https://example.com~~",120			Position:    18,121			Expected:    "https://example.com",122		},123		{124			Description: "link with angle brackets",125			Input:       "<b>We use http://example.com</b>",126			Position:    14,127			Expected:    "http://example.com",128		},129		{130			Description: "bad link protocol",131			Input:       "://///",132			Position:    0,133			Expected:    "",134		},135		{136			Description: "position greater than input length",137			Input:       "there is no colon",138			Position:    1000,139			Expected:    "",140		},141	}142	for _, testCase := range testCases {143		t.Run(testCase.Description, func(t *testing.T) {144			rawRange, ok := parseURLAutolink(testCase.Input, testCase.Position)145			if testCase.Expected == "" {146				assert.False(t, ok)147				assert.Equal(t, Range{0, 0}, rawRange)148			} else {149				assert.True(t, ok)150				assert.Equal(t, testCase.Expected, testCase.Input[rawRange.Position:rawRange.End])151			}152		})153	}154}155func TestParseWWWAutolink(t *testing.T) {156	testCases := []struct {157		Description string158		Input       string159		Position    int160		Expected    string161	}{162		{163			Description: "no link",164			Input:       "This is some text",165			Position:    0,166			Expected:    "",167		},168		{169			Description: "link",170			Input:       "www.example.com and some text",171			Position:    0,172			Expected:    "www.example.com",173		},174		{175			Description: "link with a path",176			Input:       "www.example.com/abcd and some text",177			Position:    0,178			Expected:    "www.example.com/abcd",179		},180		{181			Description: "link with parameters",182			Input:       "www.example.com/abcd?foo=bar and some text",183			Position:    0,184			Expected:    "www.example.com/abcd?foo=bar",185		},186		{187			Description: "link, not at start",188			Input:       "This is www.example.com and some text",189			Position:    8,190			Expected:    "www.example.com",191		},192		{193			Description: "link with a path, not at start",194			Input:       "This is also www.example.com/abcd and some text",195			Position:    13,196			Expected:    "www.example.com/abcd",197		},198		{199			Description: "link with parameters, not at start",200			Input:       "These are www.example.com/abcd?foo=bar and some text",201			Position:    10,202			Expected:    "www.example.com/abcd?foo=bar",203		},204		{205			Description: "link with trailing characters",206			Input:       "This is www.example.com??",207			Position:    8,208			Expected:    "www.example.com",209		},210		{211			Description: "link after current position",212			Input:       "This is some text and www.example.com",213			Position:    0,214			Expected:    "",215		},216		{217			Description: "multiple links",218			Input:       "This is www.example.com/abcd and www.example.com/1234",219			Position:    8,220			Expected:    "www.example.com/abcd",221		},222		{223			Description: "multiple links 2",224			Input:       "This is www.example.com/abcd and www.example.com/1234",225			Position:    33,226			Expected:    "www.example.com/1234",227		},228		{229			Description: "link with brackets",230			Input:       "Go to www.example.com/my/page_(disambiguation) and some text",231			Position:    6,232			Expected:    "www.example.com/my/page_(disambiguation)",233		},234		{235			Description: "link following other letters",236			Input:       "aaawww.example.com and some text",237			Position:    3,238			Expected:    "",239		},240		{241			Description: "link in brackets",242			Input:       "(www.example.com)",243			Position:    1,244			Expected:    "www.example.com",245		},246		{247			Description: "link in underscores",248			Input:       "_www.example.com_",249			Position:    1,250			Expected:    "www.example.com",251		},252		{253			Description: "link in asterisks",254			Input:       "This is **www.example.com**",255			Position:    10,256			Expected:    "www.example.com",257		},258		{259			Description: "link in strikethrough",260			Input:       "Those were ~~www.example.com~~",261			Position:    13,262			Expected:    "www.example.com",263		},264		{265			Description: "using www1",266			Input:       "Our backup site is at www1.example.com/foo",267			Position:    22,268			Expected:    "www1.example.com/foo",269		},270		{271			Description: "link with angle brackets",272			Input:       "<b>We use www2.example.com</b>",273			Position:    10,274			Expected:    "www2.example.com",275		},276	}277	for _, testCase := range testCases {278		t.Run(testCase.Description, func(t *testing.T) {279			rawRange, ok := parseWWWAutolink(testCase.Input, testCase.Position)280			if testCase.Expected == "" {281				assert.False(t, ok)282				assert.Equal(t, Range{0, 0}, rawRange)283			} else {284				assert.True(t, ok)285				assert.Equal(t, testCase.Expected, testCase.Input[rawRange.Position:rawRange.End])286			}287		})288	}289}290func TestTrimTrailingCharactersFromLink(t *testing.T) {291	testCases := []struct {292		Input       string293		Start       int294		End         int295		ExpectedEnd int296	}{297		{298			Input:       "http://www.example.com",299			ExpectedEnd: 22,300		},301		{302			Input:       "http://www.example.com/abcd",303			ExpectedEnd: 27,304		},305		{306			Input:       "http://www.example.com/abcd/",307			ExpectedEnd: 28,308		},309		{310			Input:       "http://www.example.com/1234",311			ExpectedEnd: 27,312		},313		{314			Input:       "http://www.example.com/abcd?foo=bar",315			ExpectedEnd: 35,316		},317		{318			Input:       "http://www.example.com/abcd#heading",319			ExpectedEnd: 35,320		},321		{322			Input:       "http://www.example.com.",323			ExpectedEnd: 22,324		},325		{326			Input:       "http://www.example.com,",327			ExpectedEnd: 22,328		},329		{330			Input:       "http://www.example.com?",331			ExpectedEnd: 22,332		},333		{334			Input:       "http://www.example.com)",335			ExpectedEnd: 22,336		},337		{338			Input:       "http://www.example.com",339			ExpectedEnd: 22,340		},341		{342			Input:       "https://en.wikipedia.org/wiki/Dolphin_(disambiguation)",343			ExpectedEnd: 54,344		},345		{346			Input:       "https://en.wikipedia.org/wiki/Dolphin_(disambiguation",347			ExpectedEnd: 53,348		},349		{350			Input:       "https://en.wikipedia.org/wiki/Dolphin_(disambiguation))",351			ExpectedEnd: 54,352		},353		{354			Input:       "https://en.wikipedia.org/wiki/Dolphin_(disambiguation)_(disambiguation)",355			ExpectedEnd: 71,356		},357		{358			Input:       "https://en.wikipedia.org/wiki/Dolphin_(disambiguation_(disambiguation))",359			ExpectedEnd: 71,360		},361		{362			Input:       "http://www.example.com"",363			ExpectedEnd: 22,364		},365		{366			Input:       "this is a sentence containing http://www.example.com in it",367			Start:       30,368			End:         52,369			ExpectedEnd: 52,370		},371		{372			Input:       "this is a sentence containing http://www.example.com???",373			Start:       30,374			End:         55,375			ExpectedEnd: 52,376		},377		{378			Input:       "http://google.com/Ã¥",379			ExpectedEnd: len("http://google.com/Ã¥"),380		},381		{382			Input:       "http://google.com/Ã¥...",383			ExpectedEnd: len("http://google.com/Ã¥"),384		},385		{386			Input:       "This is http://google.com/Ã¥, a link, and http://google.com/Ã¥",387			Start:       8,388			End:         len("This is http://google.com/Ã¥,"),389			ExpectedEnd: len("This is http://google.com/Ã¥"),390		},391		{392			Input:       "This is http://google.com/Ã¥, a link, and http://google.com/Ã¥",393			Start:       41,394			End:         len("This is http://google.com/Ã¥, a link, and http://google.com/Ã¥"),395			ExpectedEnd: len("This is http://google.com/Ã¥, a link, and http://google.com/Ã¥"),396		},397		{398			Input:       "This is http://google.com/Ã¥, a link, and http://google.com/Ã¥.",399			Start:       41,400			End:         len("This is http://google.com/Ã¥, a link, and http://google.com/Ã¥."),401			ExpectedEnd: len("This is http://google.com/Ã¥, a link, and http://google.com/Ã¥"),402		},403		{404			Input:       "http://ð.ga/ http://xð.ga/",405			Start:       0,406			End:         len("http://ð.ga/"),407			ExpectedEnd: len("http://ð.ga/"),408		},409		{410			Input:       "http://ð.ga/ http://xð.ga/",411			Start:       len("http://ð.ga/ "),412			End:         len("http://ð.ga/ http://xð.ga/"),413			ExpectedEnd: len("http://ð.ga/ http://xð.ga/"),414		},415	}416	for _, testCase := range testCases {417		t.Run(testCase.Input, func(t *testing.T) {418			if testCase.End == 0 {419				testCase.End = len(testCase.Input) - testCase.Start420			}421			assert.Equal(t, testCase.ExpectedEnd, trimTrailingCharactersFromLink(testCase.Input, testCase.Start, testCase.End))422		})423	}424}425func TestAutolinking(t *testing.T) {426	// These tests are adapted from https://github.com/mattermost/commonmark.js/test/mattermost.txt.427	// It is missing tests for:428	// 1. Links surrounded by emphasis (emphasis not implemented on the server)429	// 2. IPv6 addresses (not implemented on the server or by GitHub)430	// 3. Custom URL schemes (not implemented)431	for name, tc := range map[string]struct {432		Markdown     string433		ExpectedHTML string434	}{435		"valid-link-1": {436			Markdown:     `http://example.com`,437			ExpectedHTML: `<p><a href="http://example.com">http://example.com</a></p>`,438		},439		"valid-link-2": {440			Markdown:     `https://example.com`,441			ExpectedHTML: `<p><a href="https://example.com">https://example.com</a></p>`,442		},443		"valid-link-3": {444			Markdown:     `ftp://example.com`,445			ExpectedHTML: `<p><a href="ftp://example.com">ftp://example.com</a></p>`,446		},447		// "valid-link-4": {448		// 	Markdown:     `ts3server://example.com?port=9001`,449		// 	ExpectedHTML: `<p><a href="ts3server://example.com?port=9001">ts3server://example.com?port=9001</a></p>`,450		// },451		"valid-link-5": {452			Markdown:     `www.example.com`,453			ExpectedHTML: `<p><a href="http://www.example.com">www.example.com</a></p>`,454		},455		"valid-link-6": {456			Markdown:     `www.example.com/index`,457			ExpectedHTML: `<p><a href="http://www.example.com/index">www.example.com/index</a></p>`,458		},459		"valid-link-7": {460			Markdown:     `www.example.com/index.html`,461			ExpectedHTML: `<p><a href="http://www.example.com/index.html">www.example.com/index.html</a></p>`,462		},463		"valid-link-8": {464			Markdown:     `http://example.com/index/sub`,465			ExpectedHTML: `<p><a href="http://example.com/index/sub">http://example.com/index/sub</a></p>`,466		},467		"valid-link-9": {468			Markdown:     `www1.example.com`,469			ExpectedHTML: `<p><a href="http://www1.example.com">www1.example.com</a></p>`,470		},471		"valid-link-10": {472			Markdown:     `https://en.wikipedia.org/wiki/URLs#Syntax`,473			ExpectedHTML: `<p><a href="https://en.wikipedia.org/wiki/URLs#Syntax">https://en.wikipedia.org/wiki/URLs#Syntax</a></p>`,474		},475		"valid-link-11": {476			Markdown:     `https://groups.google.com/forum/#!msg`,477			ExpectedHTML: `<p><a href="https://groups.google.com/forum/#!msg">https://groups.google.com/forum/#!msg</a></p>`,478		},479		"valid-link-12": {480			Markdown:     `www.example.com/index?params=1`,481			ExpectedHTML: `<p><a href="http://www.example.com/index?params=1">www.example.com/index?params=1</a></p>`,482		},483		"valid-link-13": {484			Markdown:     `www.example.com/index?params=1&other=2`,485			ExpectedHTML: `<p><a href="http://www.example.com/index?params=1&other=2">www.example.com/index?params=1&other=2</a></p>`,486		},487		"valid-link-14": {488			Markdown:     `www.example.com/index?params=1;other=2`,489			ExpectedHTML: `<p><a href="http://www.example.com/index?params=1;other=2">www.example.com/index?params=1;other=2</a></p>`,490		},491		"valid-link-15": {492			Markdown:     `http://www.example.com/_/page`,493			ExpectedHTML: `<p><a href="http://www.example.com/_/page">http://www.example.com/_/page</a></p>`,494		},495		"valid-link-16": {496			Markdown:     `https://en.wikipedia.org/wiki/ð¬`,497			ExpectedHTML: `<p><a href="https://en.wikipedia.org/wiki/%F0%9F%90%AC">https://en.wikipedia.org/wiki/ð¬</a></p>`,498		},499		"valid-link-17": {500			Markdown:     `http://âªdf.ws/1234`,501			ExpectedHTML: `<p><a href="http://%E2%9C%AAdf.ws/1234">http://âªdf.ws/1234</a></p>`,502		},503		"valid-link-18": {504			Markdown:     `https://groups.google.com/forum/#!msg`,505			ExpectedHTML: `<p><a href="https://groups.google.com/forum/#!msg">https://groups.google.com/forum/#!msg</a></p>`,506		},507		"valid-link-19": {508			Markdown:     `https://пÑимеÑ.ÑÑб/пÑимеÑ-26/`,509			ExpectedHTML: `<p><a href="https://%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80.%D1%81%D1%80%D0%B1/%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80-26/">https://пÑимеÑ.ÑÑб/пÑимеÑ-26/</a></p>`,510		},511		"valid-link-20": {512			Markdown:     `mailto://test@example.com`,513			ExpectedHTML: `<p><a href="mailto://test@example.com">mailto://test@example.com</a></p>`,514		},515		"valid-link-21": {516			Markdown:     `tel://555-123-4567`,517			ExpectedHTML: `<p><a href="tel://555-123-4567">tel://555-123-4567</a></p>`,518		},519		"ip-address-1": {520			Markdown:     `http://127.0.0.1`,521			ExpectedHTML: `<p><a href="http://127.0.0.1">http://127.0.0.1</a></p>`,522		},523		"ip-address-2": {524			Markdown:     `http://192.168.1.1:4040`,525			ExpectedHTML: `<p><a href="http://192.168.1.1:4040">http://192.168.1.1:4040</a></p>`,526		},527		"ip-address-3": {528			Markdown:     `http://username:password@127.0.0.1`,529			ExpectedHTML: `<p><a href="http://username:password@127.0.0.1">http://username:password@127.0.0.1</a></p>`,530		},531		"ip-address-4": {532			Markdown:     `http://username:password@[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:80`,533			ExpectedHTML: `<p><a href="http://username:password@%5B2001:0:5ef5:79fb:303a:62d5:3312:ff42%5D:80">http://username:password@[2001:0:5ef5:79fb:303a:62d5:3312:ff42]:80</a></p>`,534		},535		"link-with-brackets-1": {536			Markdown:     `https://en.wikipedia.org/wiki/Rendering_(computer_graphics)`,537			ExpectedHTML: `<p><a href="https://en.wikipedia.org/wiki/Rendering_(computer_graphics)">https://en.wikipedia.org/wiki/Rendering_(computer_graphics)</a></p>`,538		},539		"link-with-brackets-2": {540			Markdown:     `http://example.com/more_(than)_one_(parens)`,541			ExpectedHTML: `<p><a href="http://example.com/more_(than)_one_(parens)">http://example.com/more_(than)_one_(parens)</a></p>`,542		},543		"link-with-brackets-3": {544			Markdown:     `http://example.com/(something)?after=parens`,545			ExpectedHTML: `<p><a href="http://example.com/(something)?after=parens">http://example.com/(something)?after=parens</a></p>`,546		},547		"link-with-brackets-4": {548			Markdown:     `http://foo.com/unicode_(âª)_in_parens`,549			ExpectedHTML: `<p><a href="http://foo.com/unicode_(%E2%9C%AA)_in_parens">http://foo.com/unicode_(âª)_in_parens</a></p>`,550		},551		"inside-another-link-1": {552			Markdown:     `[www.example.com](https://example.com)`,553			ExpectedHTML: `<p><a href="https://example.com">www.example.com</a></p>`,554		},555		"inside-another-link-2": {556			Markdown:     `[http://www.example.com](https://example.com)`,557			ExpectedHTML: `<p><a href="https://example.com">http://www.example.com</a></p>`,558		},559		"link-in-sentence-1": {560			Markdown:     `(http://example.com)`,561			ExpectedHTML: `<p>(<a href="http://example.com">http://example.com</a>)</p>`,562		},563		"link-in-sentence-2": {564			Markdown:     `(see http://example.com)`,565			ExpectedHTML: `<p>(see <a href="http://example.com">http://example.com</a>)</p>`,566		},567		"link-in-sentence-3": {568			Markdown:     `(http://example.com watch this)`,569			ExpectedHTML: `<p>(<a href="http://example.com">http://example.com</a> watch this)</p>`,570		},571		"link-in-sentence-4": {572			Markdown:     `This is a sentence with a http://example.com in it.`,573			ExpectedHTML: `<p>This is a sentence with a <a href="http://example.com">http://example.com</a> in it.</p>`,574		},575		"link-in-sentence-5": {576			Markdown:     `This is a sentence with a [link](http://example.com) in it.`,577			ExpectedHTML: `<p>This is a sentence with a <a href="http://example.com">link</a> in it.</p>`,578		},579		"link-in-sentence-6": {580			Markdown:     `This is a sentence with a http://example.com/_/underscore in it.`,581			ExpectedHTML: `<p>This is a sentence with a <a href="http://example.com/_/underscore">http://example.com/_/underscore</a> in it.</p>`,582		},583		"link-in-sentence-7": {584			Markdown:     `This is a sentence with a link (http://example.com) in it.`,585			ExpectedHTML: `<p>This is a sentence with a link (<a href="http://example.com">http://example.com</a>) in it.</p>`,586		},587		"link-in-sentence-8": {588			Markdown:     `This is a sentence with a (https://en.wikipedia.org/wiki/Rendering_(computer_graphics)) in it.`,589			ExpectedHTML: `<p>This is a sentence with a (<a href="https://en.wikipedia.org/wiki/Rendering_(computer_graphics)">https://en.wikipedia.org/wiki/Rendering_(computer_graphics)</a>) in it.</p>`,590		},591		"link-in-sentence-9": {592			Markdown:     `This is a sentence with a http://192.168.1.1:4040 in it.`,593			ExpectedHTML: `<p>This is a sentence with a <a href="http://192.168.1.1:4040">http://192.168.1.1:4040</a> in it.</p>`,594		},595		"link-in-sentence-10": {596			Markdown:     `This is a link to http://example.com.`,597			ExpectedHTML: `<p>This is a link to <a href="http://example.com">http://example.com</a>.</p>`,598		},599		"link-in-sentence-11": {600			Markdown:     `This is a link to http://example.com*`,601			ExpectedHTML: `<p>This is a link to <a href="http://example.com">http://example.com</a>*</p>`,602		},603		"link-in-sentence-12": {604			Markdown:     `This is a link to http://example.com_`,605			ExpectedHTML: `<p>This is a link to <a href="http://example.com">http://example.com</a>_</p>`,606		},607		"link-in-sentence-13": {608			Markdown:     `This is a link containing http://example.com/something?with,commas,in,url, but not at the end`,609			ExpectedHTML: `<p>This is a link containing <a href="http://example.com/something?with,commas,in,url">http://example.com/something?with,commas,in,url</a>, but not at the end</p>`,610		},611		"link-in-sentence-14": {612			Markdown:     `This is a question about a link http://example.com?`,613			ExpectedHTML: `<p>This is a question about a link <a href="http://example.com">http://example.com</a>?</p>`,614		},615		"plt-7250-link-with-trailing-periods-1": {616			Markdown:     `http://example.com.`,617			ExpectedHTML: `<p><a href="http://example.com">http://example.com</a>.</p>`,618		},619		"plt-7250-link-with-trailing-periods-2": {620			Markdown:     `http://example.com...`,621			ExpectedHTML: `<p><a href="http://example.com">http://example.com</a>...</p>`,622		},623		"plt-7250-link-with-trailing-periods-3": {624			Markdown:     `http://example.com/foo.`,625			ExpectedHTML: `<p><a href="http://example.com/foo">http://example.com/foo</a>.</p>`,626		},627		"plt-7250-link-with-trailing-periods-4": {628			Markdown:     `http://example.com/foo...`,629			ExpectedHTML: `<p><a href="http://example.com/foo">http://example.com/foo</a>...</p>`,630		},631		"plt-7250-link-with-trailing-periods-5": {632			Markdown:     `http://example.com/foo.bar`,633			ExpectedHTML: `<p><a href="http://example.com/foo.bar">http://example.com/foo.bar</a></p>`,634		},635		"plt-7250-link-with-trailing-periods-6": {636			Markdown:     `http://example.com/foo...bar`,637			ExpectedHTML: `<p><a href="http://example.com/foo...bar">http://example.com/foo...bar</a></p>`,638		},639		"rn-319-www-link-as-part-of-word-1": {640			Markdown:     `testwww.example.com`,641			ExpectedHTML: `<p>testwww.example.com</p>`,642		},643		"mm-10180-link-containing-period-followed-by-non-letter-1": {644			Markdown:     `https://example.com/123.+Pagetitle`,645			ExpectedHTML: `<p><a href="https://example.com/123.+Pagetitle">https://example.com/123.+Pagetitle</a></p>`,646		},647		"mm-10180-link-containing-period-followed-by-non-letter-2": {648			Markdown:     `https://example.com/123.?Pagetitle`,649			ExpectedHTML: `<p><a href="https://example.com/123.?Pagetitle">https://example.com/123.?Pagetitle</a></p>`,650		},651		"mm-10180-link-containing-period-followed-by-non-letter-3": {652			Markdown:     `https://example.com/123.-Pagetitle`,653			ExpectedHTML: `<p><a href="https://example.com/123.-Pagetitle">https://example.com/123.-Pagetitle</a></p>`,654		},655		"mm-10180-link-containing-period-followed-by-non-letter-4": {656			Markdown:     `https://example.com/123._Pagetitle`,657			ExpectedHTML: `<p><a href="https://example.com/123._Pagetitle">https://example.com/123._Pagetitle</a></p>`,658		},659		"mm-10180-link-containing-period-followed-by-non-letter-5": {660			Markdown:     `https://example.com/123.+`,661			ExpectedHTML: `<p><a href="https://example.com/123.+">https://example.com/123.+</a></p>`,662		},663		"mm-10180-link-containing-period-followed-by-non-letter-6": {664			Markdown:     `https://example.com/123.?`,665			ExpectedHTML: `<p><a href="https://example.com/123">https://example.com/123</a>.?</p>`,666		},667		"mm-10180-link-containing-period-followed-by-non-letter-7": {668			Markdown:     `https://example.com/123.-`,669			ExpectedHTML: `<p><a href="https://example.com/123.-">https://example.com/123.-</a></p>`,670		},671		"mm-10180-link-containing-period-followed-by-non-letter-8": {672			Markdown:     `https://example.com/123._`,673			ExpectedHTML: `<p><a href="https://example.com/123">https://example.com/123</a>._</p>`,674		},675	} {676		t.Run(name, func(t *testing.T) {677			assert.Equal(t, tc.ExpectedHTML, RenderHTML(tc.Markdown))678		})679	}680}...message_test.go
Source:message_test.go  
1// Copyright 2011 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4package mail5import (6	"bytes"7	"io"8	"io/ioutil"9	"mime"10	"reflect"11	"strings"12	"testing"13	"time"14)15var parseTests = []struct {16	in     string17	header Header18	body   string19}{20	{21		// RFC 5322, Appendix A.1.122		in: `From: John Doe <jdoe@machine.example>23To: Mary Smith <mary@example.net>24Subject: Saying Hello25Date: Fri, 21 Nov 1997 09:55:06 -060026Message-ID: <1234@local.machine.example>27This is a message just to say hello.28So, "Hello".29`,30		header: Header{31			"From":       []string{"John Doe <jdoe@machine.example>"},32			"To":         []string{"Mary Smith <mary@example.net>"},33			"Subject":    []string{"Saying Hello"},34			"Date":       []string{"Fri, 21 Nov 1997 09:55:06 -0600"},35			"Message-Id": []string{"<1234@local.machine.example>"},36		},37		body: "This is a message just to say hello.\nSo, \"Hello\".\n",38	},39}40func TestParsing(t *testing.T) {41	for i, test := range parseTests {42		msg, err := ReadMessage(bytes.NewBuffer([]byte(test.in)))43		if err != nil {44			t.Errorf("test #%d: Failed parsing message: %v", i, err)45			continue46		}47		if !headerEq(msg.Header, test.header) {48			t.Errorf("test #%d: Incorrectly parsed message header.\nGot:\n%+v\nWant:\n%+v",49				i, msg.Header, test.header)50		}51		body, err := ioutil.ReadAll(msg.Body)52		if err != nil {53			t.Errorf("test #%d: Failed reading body: %v", i, err)54			continue55		}56		bodyStr := string(body)57		if bodyStr != test.body {58			t.Errorf("test #%d: Incorrectly parsed message body.\nGot:\n%+v\nWant:\n%+v",59				i, bodyStr, test.body)60		}61	}62}63func headerEq(a, b Header) bool {64	if len(a) != len(b) {65		return false66	}67	for k, as := range a {68		bs, ok := b[k]69		if !ok {70			return false71		}72		if !reflect.DeepEqual(as, bs) {73			return false74		}75	}76	return true77}78func TestDateParsing(t *testing.T) {79	tests := []struct {80		dateStr string81		exp     time.Time82	}{83		// RFC 5322, Appendix A.1.184		{85			"Fri, 21 Nov 1997 09:55:06 -0600",86			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),87		},88		// RFC 5322, Appendix A.6.289		// Obsolete date.90		{91			"21 Nov 97 09:55:06 GMT",92			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("GMT", 0)),93		},94		// Commonly found format not specified by RFC 5322.95		{96			"Fri, 21 Nov 1997 09:55:06 -0600 (MDT)",97			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),98		},99	}100	for _, test := range tests {101		hdr := Header{102			"Date": []string{test.dateStr},103		}104		date, err := hdr.Date()105		if err != nil {106			t.Errorf("Header(Date: %s).Date(): %v", test.dateStr, err)107		} else if !date.Equal(test.exp) {108			t.Errorf("Header(Date: %s).Date() = %+v, want %+v", test.dateStr, date, test.exp)109		}110		date, err = ParseDate(test.dateStr)111		if err != nil {112			t.Errorf("ParseDate(%s): %v", test.dateStr, err)113		} else if !date.Equal(test.exp) {114			t.Errorf("ParseDate(%s) = %+v, want %+v", test.dateStr, date, test.exp)115		}116	}117}118func TestAddressParsingError(t *testing.T) {119	mustErrTestCases := [...]struct {120		text        string121		wantErrText string122	}{123		0:  {"=?iso-8859-2?Q?Bogl=E1rka_Tak=E1cs?= <unknown@gmail.com>", "charset not supported"},124		1:  {"a@gmail.com b@gmail.com", "expected single address"},125		2:  {string([]byte{0xed, 0xa0, 0x80}) + " <micro@example.net>", "invalid utf-8 in address"},126		3:  {"\"" + string([]byte{0xed, 0xa0, 0x80}) + "\" <half-surrogate@example.com>", "invalid utf-8 in quoted-string"},127		4:  {"\"\\" + string([]byte{0x80}) + "\" <escaped-invalid-unicode@example.net>", "invalid utf-8 in quoted-string"},128		5:  {"\"\x00\" <null@example.net>", "bad character in quoted-string"},129		6:  {"\"\\\x00\" <escaped-null@example.net>", "bad character in quoted-string"},130		7:  {"John Doe", "no angle-addr"},131		8:  {`<jdoe#machine.example>`, "missing @ in addr-spec"},132		9:  {`John <middle> Doe <jdoe@machine.example>`, "missing @ in addr-spec"},133		10: {"cfws@example.com (", "misformatted parenthetical comment"},134		11: {"empty group: ;", "empty group"},135		12: {"root group: embed group: null@example.com;", "no angle-addr"},136		13: {"group not closed: null@example.com", "expected comma"},137		14: {"group: first@example.com, second@example.com;", "group with multiple addresses"},138	}139	for i, tc := range mustErrTestCases {140		_, err := ParseAddress(tc.text)141		if err == nil || !strings.Contains(err.Error(), tc.wantErrText) {142			t.Errorf(`mail.ParseAddress(%q) #%d want %q, got %v`, tc.text, i, tc.wantErrText, err)143		}144	}145}146func TestAddressParsing(t *testing.T) {147	tests := []struct {148		addrsStr string149		exp      []*Address150	}{151		// Bare address152		{153			`jdoe@machine.example`,154			[]*Address{{155				Address: "jdoe@machine.example",156			}},157		},158		// RFC 5322, Appendix A.1.1159		{160			`John Doe <jdoe@machine.example>`,161			[]*Address{{162				Name:    "John Doe",163				Address: "jdoe@machine.example",164			}},165		},166		// RFC 5322, Appendix A.1.2167		{168			`"Joe Q. Public" <john.q.public@example.com>`,169			[]*Address{{170				Name:    "Joe Q. Public",171				Address: "john.q.public@example.com",172			}},173		},174		{175			`"John (middle) Doe" <jdoe@machine.example>`,176			[]*Address{{177				Name:    "John (middle) Doe",178				Address: "jdoe@machine.example",179			}},180		},181		{182			`John (middle) Doe <jdoe@machine.example>`,183			[]*Address{{184				Name:    "John (middle) Doe",185				Address: "jdoe@machine.example",186			}},187		},188		{189			`John !@M@! Doe <jdoe@machine.example>`,190			[]*Address{{191				Name:    "John !@M@! Doe",192				Address: "jdoe@machine.example",193			}},194		},195		{196			`"John <middle> Doe" <jdoe@machine.example>`,197			[]*Address{{198				Name:    "John <middle> Doe",199				Address: "jdoe@machine.example",200			}},201		},202		{203			`Mary Smith <mary@x.test>, jdoe@example.org, Who? <one@y.test>`,204			[]*Address{205				{206					Name:    "Mary Smith",207					Address: "mary@x.test",208				},209				{210					Address: "jdoe@example.org",211				},212				{213					Name:    "Who?",214					Address: "one@y.test",215				},216			},217		},218		{219			`<boss@nil.test>, "Giant; \"Big\" Box" <sysservices@example.net>`,220			[]*Address{221				{222					Address: "boss@nil.test",223				},224				{225					Name:    `Giant; "Big" Box`,226					Address: "sysservices@example.net",227				},228			},229		},230		// RFC 5322, Appendix A.6.1231		{232			`Joe Q. Public <john.q.public@example.com>`,233			[]*Address{{234				Name:    "Joe Q. Public",235				Address: "john.q.public@example.com",236			}},237		},238		// RFC 5322, Appendix A.1.3239		{240			`group1: groupaddr1@example.com;`,241			[]*Address{242				{243					Name:    "",244					Address: "groupaddr1@example.com",245				},246			},247		},248		{249			`empty group: ;`,250			[]*Address(nil),251		},252		{253			`A Group:Ed Jones <c@a.test>,joe@where.test,John <jdoe@one.test>;`,254			[]*Address{255				{256					Name:    "Ed Jones",257					Address: "c@a.test",258				},259				{260					Name:    "",261					Address: "joe@where.test",262				},263				{264					Name:    "John",265					Address: "jdoe@one.test",266				},267			},268		},269		{270			`Group1: <addr1@example.com>;, Group 2: addr2@example.com;, John <addr3@example.com>`,271			[]*Address{272				{273					Name:    "",274					Address: "addr1@example.com",275				},276				{277					Name:    "",278					Address: "addr2@example.com",279				},280				{281					Name:    "John",282					Address: "addr3@example.com",283				},284			},285		},286		// RFC 2047 "Q"-encoded ISO-8859-1 address.287		{288			`=?iso-8859-1?q?J=F6rg_Doe?= <joerg@example.com>`,289			[]*Address{290				{291					Name:    `Jörg Doe`,292					Address: "joerg@example.com",293				},294			},295		},296		// RFC 2047 "Q"-encoded US-ASCII address. Dumb but legal.297		{298			`=?us-ascii?q?J=6Frg_Doe?= <joerg@example.com>`,299			[]*Address{300				{301					Name:    `Jorg Doe`,302					Address: "joerg@example.com",303				},304			},305		},306		// RFC 2047 "Q"-encoded UTF-8 address.307		{308			`=?utf-8?q?J=C3=B6rg_Doe?= <joerg@example.com>`,309			[]*Address{310				{311					Name:    `Jörg Doe`,312					Address: "joerg@example.com",313				},314			},315		},316		// RFC 2047 "Q"-encoded UTF-8 address with multiple encoded-words.317		{318			`=?utf-8?q?J=C3=B6rg?=  =?utf-8?q?Doe?= <joerg@example.com>`,319			[]*Address{320				{321					Name:    `JörgDoe`,322					Address: "joerg@example.com",323				},324			},325		},326		// RFC 2047, Section 8.327		{328			`=?ISO-8859-1?Q?Andr=E9?= Pirard <PIRARD@vm1.ulg.ac.be>`,329			[]*Address{330				{331					Name:    `André Pirard`,332					Address: "PIRARD@vm1.ulg.ac.be",333				},334			},335		},336		// Custom example of RFC 2047 "B"-encoded ISO-8859-1 address.337		{338			`=?ISO-8859-1?B?SvZyZw==?= <joerg@example.com>`,339			[]*Address{340				{341					Name:    `Jörg`,342					Address: "joerg@example.com",343				},344			},345		},346		// Custom example of RFC 2047 "B"-encoded UTF-8 address.347		{348			`=?UTF-8?B?SsO2cmc=?= <joerg@example.com>`,349			[]*Address{350				{351					Name:    `Jörg`,352					Address: "joerg@example.com",353				},354			},355		},356		// Custom example with "." in name. For issue 4938357		{358			`Asem H. <noreply@example.com>`,359			[]*Address{360				{361					Name:    `Asem H.`,362					Address: "noreply@example.com",363				},364			},365		},366		// RFC 6532 3.2.3, qtext /= UTF8-non-ascii367		{368			`"Gø Pher" <gopher@example.com>`,369			[]*Address{370				{371					Name:    `Gø Pher`,372					Address: "gopher@example.com",373				},374			},375		},376		// RFC 6532 3.2, atext /= UTF8-non-ascii377		{378			`µ <micro@example.com>`,379			[]*Address{380				{381					Name:    `µ`,382					Address: "micro@example.com",383				},384			},385		},386		// RFC 6532 3.2.2, local address parts allow UTF-8387		{388			`Micro <µ@example.com>`,389			[]*Address{390				{391					Name:    `Micro`,392					Address: "µ@example.com",393				},394			},395		},396		// RFC 6532 3.2.4, domains parts allow UTF-8397		{398			`Micro <micro@µ.example.com>`,399			[]*Address{400				{401					Name:    `Micro`,402					Address: "micro@µ.example.com",403				},404			},405		},406		// Issue 14866407		{408			`"" <emptystring@example.com>`,409			[]*Address{410				{411					Name:    "",412					Address: "emptystring@example.com",413				},414			},415		},416		// CFWS417		{418			`<cfws@example.com> (CFWS (cfws))  (another comment)`,419			[]*Address{420				{421					Name:    "",422					Address: "cfws@example.com",423				},424			},425		},426		{427			`<cfws@example.com> ()  (another comment), <cfws2@example.com> (another)`,428			[]*Address{429				{430					Name:    "",431					Address: "cfws@example.com",432				},433				{434					Name:    "",435					Address: "cfws2@example.com",436				},437			},438		},439		// Comment as display name440		{441			`john@example.com (John Doe)`,442			[]*Address{443				{444					Name:    "John Doe",445					Address: "john@example.com",446				},447			},448		},449		// Comment and display name450		{451			`John Doe <john@example.com> (Joey)`,452			[]*Address{453				{454					Name:    "John Doe",455					Address: "john@example.com",456				},457			},458		},459		// Comment as display name, no space460		{461			`john@example.com(John Doe)`,462			[]*Address{463				{464					Name:    "John Doe",465					Address: "john@example.com",466				},467			},468		},469		// Comment as display name, Q-encoded470		{471			`asjo@example.com (Adam =?utf-8?Q?Sj=C3=B8gren?=)`,472			[]*Address{473				{474					Name:    "Adam Sjøgren",475					Address: "asjo@example.com",476				},477			},478		},479		// Comment as display name, Q-encoded and tab-separated480		{481			`asjo@example.com (Adam	=?utf-8?Q?Sj=C3=B8gren?=)`,482			[]*Address{483				{484					Name:    "Adam Sjøgren",485					Address: "asjo@example.com",486				},487			},488		},489		// Nested comment as display name, Q-encoded490		{491			`asjo@example.com (Adam =?utf-8?Q?Sj=C3=B8gren?= (Debian))`,492			[]*Address{493				{494					Name:    "Adam Sjøgren (Debian)",495					Address: "asjo@example.com",496				},497			},498		},499	}500	for _, test := range tests {501		if len(test.exp) == 1 {502			addr, err := ParseAddress(test.addrsStr)503			if err != nil {504				t.Errorf("Failed parsing (single) %q: %v", test.addrsStr, err)505				continue506			}507			if !reflect.DeepEqual([]*Address{addr}, test.exp) {508				t.Errorf("Parse (single) of %q: got %+v, want %+v", test.addrsStr, addr, test.exp)509			}510		}511		addrs, err := ParseAddressList(test.addrsStr)512		if err != nil {513			t.Errorf("Failed parsing (list) %q: %v", test.addrsStr, err)514			continue515		}516		if !reflect.DeepEqual(addrs, test.exp) {517			t.Errorf("Parse (list) of %q: got %+v, want %+v", test.addrsStr, addrs, test.exp)518		}519	}520}521func TestAddressParser(t *testing.T) {522	tests := []struct {523		addrsStr string524		exp      []*Address525	}{526		// Bare address527		{528			`jdoe@machine.example`,529			[]*Address{{530				Address: "jdoe@machine.example",531			}},532		},533		// RFC 5322, Appendix A.1.1534		{535			`John Doe <jdoe@machine.example>`,536			[]*Address{{537				Name:    "John Doe",538				Address: "jdoe@machine.example",539			}},540		},541		// RFC 5322, Appendix A.1.2542		{543			`"Joe Q. Public" <john.q.public@example.com>`,544			[]*Address{{545				Name:    "Joe Q. Public",546				Address: "john.q.public@example.com",547			}},548		},549		{550			`Mary Smith <mary@x.test>, jdoe@example.org, Who? <one@y.test>`,551			[]*Address{552				{553					Name:    "Mary Smith",554					Address: "mary@x.test",555				},556				{557					Address: "jdoe@example.org",558				},559				{560					Name:    "Who?",561					Address: "one@y.test",562				},563			},564		},565		{566			`<boss@nil.test>, "Giant; \"Big\" Box" <sysservices@example.net>`,567			[]*Address{568				{569					Address: "boss@nil.test",570				},571				{572					Name:    `Giant; "Big" Box`,573					Address: "sysservices@example.net",574				},575			},576		},577		// RFC 2047 "Q"-encoded ISO-8859-1 address.578		{579			`=?iso-8859-1?q?J=F6rg_Doe?= <joerg@example.com>`,580			[]*Address{581				{582					Name:    `Jörg Doe`,583					Address: "joerg@example.com",584				},585			},586		},587		// RFC 2047 "Q"-encoded US-ASCII address. Dumb but legal.588		{589			`=?us-ascii?q?J=6Frg_Doe?= <joerg@example.com>`,590			[]*Address{591				{592					Name:    `Jorg Doe`,593					Address: "joerg@example.com",594				},595			},596		},597		// RFC 2047 "Q"-encoded ISO-8859-15 address.598		{599			`=?ISO-8859-15?Q?J=F6rg_Doe?= <joerg@example.com>`,600			[]*Address{601				{602					Name:    `Jörg Doe`,603					Address: "joerg@example.com",604				},605			},606		},607		// RFC 2047 "B"-encoded windows-1252 address.608		{609			`=?windows-1252?q?Andr=E9?= Pirard <PIRARD@vm1.ulg.ac.be>`,610			[]*Address{611				{612					Name:    `André Pirard`,613					Address: "PIRARD@vm1.ulg.ac.be",614				},615			},616		},617		// Custom example of RFC 2047 "B"-encoded ISO-8859-15 address.618		{619			`=?ISO-8859-15?B?SvZyZw==?= <joerg@example.com>`,620			[]*Address{621				{622					Name:    `Jörg`,623					Address: "joerg@example.com",624				},625			},626		},627		// Custom example of RFC 2047 "B"-encoded UTF-8 address.628		{629			`=?UTF-8?B?SsO2cmc=?= <joerg@example.com>`,630			[]*Address{631				{632					Name:    `Jörg`,633					Address: "joerg@example.com",634				},635			},636		},637		// Custom example with "." in name. For issue 4938638		{639			`Asem H. <noreply@example.com>`,640			[]*Address{641				{642					Name:    `Asem H.`,643					Address: "noreply@example.com",644				},645			},646		},647	}648	ap := AddressParser{WordDecoder: &mime.WordDecoder{649		CharsetReader: func(charset string, input io.Reader) (io.Reader, error) {650			in, err := ioutil.ReadAll(input)651			if err != nil {652				return nil, err653			}654			switch charset {655			case "iso-8859-15":656				in = bytes.Replace(in, []byte("\xf6"), []byte("ö"), -1)657			case "windows-1252":658				in = bytes.Replace(in, []byte("\xe9"), []byte("é"), -1)659			}660			return bytes.NewReader(in), nil661		},662	}}663	for _, test := range tests {664		if len(test.exp) == 1 {665			addr, err := ap.Parse(test.addrsStr)666			if err != nil {667				t.Errorf("Failed parsing (single) %q: %v", test.addrsStr, err)668				continue669			}670			if !reflect.DeepEqual([]*Address{addr}, test.exp) {671				t.Errorf("Parse (single) of %q: got %+v, want %+v", test.addrsStr, addr, test.exp)672			}673		}674		addrs, err := ap.ParseList(test.addrsStr)675		if err != nil {676			t.Errorf("Failed parsing (list) %q: %v", test.addrsStr, err)677			continue678		}679		if !reflect.DeepEqual(addrs, test.exp) {680			t.Errorf("Parse (list) of %q: got %+v, want %+v", test.addrsStr, addrs, test.exp)681		}682	}683}684func TestAddressString(t *testing.T) {685	tests := []struct {686		addr *Address687		exp  string688	}{689		{690			&Address{Address: "bob@example.com"},691			"<bob@example.com>",692		},693		{ // quoted local parts: RFC 5322, 3.4.1. and 3.2.4.694			&Address{Address: `my@idiot@address@example.com`},695			`<"my@idiot@address"@example.com>`,696		},697		{ // quoted local parts698			&Address{Address: ` @example.com`},699			`<" "@example.com>`,700		},701		{702			&Address{Name: "Bob", Address: "bob@example.com"},703			`"Bob" <bob@example.com>`,704		},705		{706			// note the ö (o with an umlaut)707			&Address{Name: "Böb", Address: "bob@example.com"},708			`=?utf-8?q?B=C3=B6b?= <bob@example.com>`,709		},710		{711			&Address{Name: "Bob Jane", Address: "bob@example.com"},712			`"Bob Jane" <bob@example.com>`,713		},714		{715			&Address{Name: "Böb Jacöb", Address: "bob@example.com"},716			`=?utf-8?q?B=C3=B6b_Jac=C3=B6b?= <bob@example.com>`,717		},718		{ // https://golang.org/issue/12098719			&Address{Name: "Rob", Address: ""},720			`"Rob" <@>`,721		},722		{ // https://golang.org/issue/12098723			&Address{Name: "Rob", Address: "@"},724			`"Rob" <@>`,725		},726		{727			&Address{Name: "Böb, Jacöb", Address: "bob@example.com"},728			`=?utf-8?b?QsO2YiwgSmFjw7Zi?= <bob@example.com>`,729		},730		{731			&Address{Name: "=??Q?x?=", Address: "hello@world.com"},732			`"=??Q?x?=" <hello@world.com>`,733		},734		{735			&Address{Name: "=?hello", Address: "hello@world.com"},736			`"=?hello" <hello@world.com>`,737		},738		{739			&Address{Name: "world?=", Address: "hello@world.com"},740			`"world?=" <hello@world.com>`,741		},742		{743			// should q-encode even for invalid utf-8.744			&Address{Name: string([]byte{0xed, 0xa0, 0x80}), Address: "invalid-utf8@example.net"},745			"=?utf-8?q?=ED=A0=80?= <invalid-utf8@example.net>",746		},747	}748	for _, test := range tests {749		s := test.addr.String()750		if s != test.exp {751			t.Errorf("Address%+v.String() = %v, want %v", *test.addr, s, test.exp)752			continue753		}754		// Check round-trip.755		if test.addr.Address != "" && test.addr.Address != "@" {756			a, err := ParseAddress(test.exp)757			if err != nil {758				t.Errorf("ParseAddress(%#q): %v", test.exp, err)759				continue760			}761			if a.Name != test.addr.Name || a.Address != test.addr.Address {762				t.Errorf("ParseAddress(%#q) = %#v, want %#v", test.exp, a, test.addr)763			}764		}765	}766}767// Check if all valid addresses can be parsed, formatted and parsed again768func TestAddressParsingAndFormatting(t *testing.T) {769	// Should pass770	tests := []string{771		`<Bob@example.com>`,772		`<bob.bob@example.com>`,773		`<".bob"@example.com>`,774		`<" "@example.com>`,775		`<some.mail-with-dash@example.com>`,776		`<"dot.and space"@example.com>`,777		`<"very.unusual.@.unusual.com"@example.com>`,778		`<admin@mailserver1>`,779		`<postmaster@localhost>`,780		"<#!$%&'*+-/=?^_`{}|~@example.org>",781		`<"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com>`, // escaped quotes782		`<"()<>[]:,;@\\\"!#$%&'*+-/=?^_{}| ~.a"@example.org>`,                      // escaped backslashes783		`<"Abc\\@def"@example.com>`,784		`<"Joe\\Blow"@example.com>`,785		`<test1/test2=test3@example.com>`,786		`<def!xyz%abc@example.com>`,787		`<_somename@example.com>`,788		`<joe@uk>`,789		`<~@example.com>`,790		`<"..."@test.com>`,791		`<"john..doe"@example.com>`,792		`<"john.doe."@example.com>`,793		`<".john.doe"@example.com>`,794		`<"."@example.com>`,795		`<".."@example.com>`,796		`<"0:"@0>`,797	}798	for _, test := range tests {799		addr, err := ParseAddress(test)800		if err != nil {801			t.Errorf("Couldn't parse address %s: %s", test, err.Error())802			continue803		}804		str := addr.String()805		addr, err = ParseAddress(str)806		if err != nil {807			t.Errorf("ParseAddr(%q) error: %v", test, err)808			continue809		}810		if addr.String() != test {811			t.Errorf("String() round-trip = %q; want %q", addr, test)812			continue813		}814	}815	// Should fail816	badTests := []string{817		`<Abc.example.com>`,818		`<A@b@c@example.com>`,819		`<a"b(c)d,e:f;g<h>i[j\k]l@example.com>`,820		`<just"not"right@example.com>`,821		`<this is"not\allowed@example.com>`,822		`<this\ still\"not\\allowed@example.com>`,823		`<john..doe@example.com>`,824		`<john.doe@example..com>`,825		`<john.doe@example..com>`,826		`<john.doe.@example.com>`,827		`<john.doe.@.example.com>`,828		`<.john.doe@example.com>`,829		`<@example.com>`,830		`<.@example.com>`,831		`<test@.>`,832		`< @example.com>`,833		`<""test""blah""@example.com>`,834		`<""@0>`,835	}836	for _, test := range badTests {837		_, err := ParseAddress(test)838		if err == nil {839			t.Errorf("Should have failed to parse address: %s", test)840			continue841		}842	}843}844func TestAddressFormattingAndParsing(t *testing.T) {845	tests := []*Address{846		{Name: "@lïce", Address: "alice@example.com"},847		{Name: "Böb O'Connor", Address: "bob@example.com"},848		{Name: "???", Address: "bob@example.com"},849		{Name: "Böb ???", Address: "bob@example.com"},850		{Name: "Böb (Jacöb)", Address: "bob@example.com"},851		{Name: "à#$%&'(),.:;<>@[]^`{|}~'", Address: "bob@example.com"},852		// https://golang.org/issue/11292853		{Name: "\"\\\x1f,\"", Address: "0@0"},854		// https://golang.org/issue/12782855		{Name: "naé, mée", Address: "test.mail@gmail.com"},856	}857	for i, test := range tests {858		parsed, err := ParseAddress(test.String())859		if err != nil {860			t.Errorf("test #%d: ParseAddr(%q) error: %v", i, test.String(), err)861			continue862		}863		if parsed.Name != test.Name {864			t.Errorf("test #%d: Parsed name = %q; want %q", i, parsed.Name, test.Name)865		}866		if parsed.Address != test.Address {867			t.Errorf("test #%d: Parsed address = %q; want %q", i, parsed.Address, test.Address)868		}869	}870}...zz_generated.conversion.go
Source:zz_generated.conversion.go  
1// +build !ignore_autogenerated2/*3Copyright The Kubernetes Authors.4Licensed under the Apache License, Version 2.0 (the "License");5you may not use this file except in compliance with the License.6You may obtain a copy of the License at7    http://www.apache.org/licenses/LICENSE-2.08Unless required by applicable law or agreed to in writing, software9distributed under the License is distributed on an "AS IS" BASIS,10WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11See the License for the specific language governing permissions and12limitations under the License.13*/14// Code generated by conversion-gen. DO NOT EDIT.15package v116import (17	unsafe "unsafe"18	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"19	conversion "k8s.io/apimachinery/pkg/conversion"20	runtime "k8s.io/apimachinery/pkg/runtime"21	example "k8s.io/apiserver/pkg/apis/example"22)23func init() {24	localSchemeBuilder.Register(RegisterConversions)25}26// RegisterConversions adds conversion functions to the given scheme.27// Public to allow building arbitrary schemes.28func RegisterConversions(s *runtime.Scheme) error {29	if err := s.AddGeneratedConversionFunc((*Pod)(nil), (*example.Pod)(nil), func(a, b interface{}, scope conversion.Scope) error {30		return Convert_v1_Pod_To_example_Pod(a.(*Pod), b.(*example.Pod), scope)31	}); err != nil {32		return err33	}34	if err := s.AddGeneratedConversionFunc((*example.Pod)(nil), (*Pod)(nil), func(a, b interface{}, scope conversion.Scope) error {35		return Convert_example_Pod_To_v1_Pod(a.(*example.Pod), b.(*Pod), scope)36	}); err != nil {37		return err38	}39	if err := s.AddGeneratedConversionFunc((*PodCondition)(nil), (*example.PodCondition)(nil), func(a, b interface{}, scope conversion.Scope) error {40		return Convert_v1_PodCondition_To_example_PodCondition(a.(*PodCondition), b.(*example.PodCondition), scope)41	}); err != nil {42		return err43	}44	if err := s.AddGeneratedConversionFunc((*example.PodCondition)(nil), (*PodCondition)(nil), func(a, b interface{}, scope conversion.Scope) error {45		return Convert_example_PodCondition_To_v1_PodCondition(a.(*example.PodCondition), b.(*PodCondition), scope)46	}); err != nil {47		return err48	}49	if err := s.AddGeneratedConversionFunc((*PodList)(nil), (*example.PodList)(nil), func(a, b interface{}, scope conversion.Scope) error {50		return Convert_v1_PodList_To_example_PodList(a.(*PodList), b.(*example.PodList), scope)51	}); err != nil {52		return err53	}54	if err := s.AddGeneratedConversionFunc((*example.PodList)(nil), (*PodList)(nil), func(a, b interface{}, scope conversion.Scope) error {55		return Convert_example_PodList_To_v1_PodList(a.(*example.PodList), b.(*PodList), scope)56	}); err != nil {57		return err58	}59	if err := s.AddGeneratedConversionFunc((*PodSpec)(nil), (*example.PodSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {60		return Convert_v1_PodSpec_To_example_PodSpec(a.(*PodSpec), b.(*example.PodSpec), scope)61	}); err != nil {62		return err63	}64	if err := s.AddGeneratedConversionFunc((*example.PodSpec)(nil), (*PodSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {65		return Convert_example_PodSpec_To_v1_PodSpec(a.(*example.PodSpec), b.(*PodSpec), scope)66	}); err != nil {67		return err68	}69	if err := s.AddGeneratedConversionFunc((*PodStatus)(nil), (*example.PodStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {70		return Convert_v1_PodStatus_To_example_PodStatus(a.(*PodStatus), b.(*example.PodStatus), scope)71	}); err != nil {72		return err73	}74	if err := s.AddGeneratedConversionFunc((*example.PodStatus)(nil), (*PodStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {75		return Convert_example_PodStatus_To_v1_PodStatus(a.(*example.PodStatus), b.(*PodStatus), scope)76	}); err != nil {77		return err78	}79	return nil80}81func autoConvert_v1_Pod_To_example_Pod(in *Pod, out *example.Pod, s conversion.Scope) error {82	out.ObjectMeta = in.ObjectMeta83	if err := Convert_v1_PodSpec_To_example_PodSpec(&in.Spec, &out.Spec, s); err != nil {84		return err85	}86	if err := Convert_v1_PodStatus_To_example_PodStatus(&in.Status, &out.Status, s); err != nil {87		return err88	}89	return nil90}91// Convert_v1_Pod_To_example_Pod is an autogenerated conversion function.92func Convert_v1_Pod_To_example_Pod(in *Pod, out *example.Pod, s conversion.Scope) error {93	return autoConvert_v1_Pod_To_example_Pod(in, out, s)94}95func autoConvert_example_Pod_To_v1_Pod(in *example.Pod, out *Pod, s conversion.Scope) error {96	out.ObjectMeta = in.ObjectMeta97	if err := Convert_example_PodSpec_To_v1_PodSpec(&in.Spec, &out.Spec, s); err != nil {98		return err99	}100	if err := Convert_example_PodStatus_To_v1_PodStatus(&in.Status, &out.Status, s); err != nil {101		return err102	}103	return nil104}105// Convert_example_Pod_To_v1_Pod is an autogenerated conversion function.106func Convert_example_Pod_To_v1_Pod(in *example.Pod, out *Pod, s conversion.Scope) error {107	return autoConvert_example_Pod_To_v1_Pod(in, out, s)108}109func autoConvert_v1_PodCondition_To_example_PodCondition(in *PodCondition, out *example.PodCondition, s conversion.Scope) error {110	out.Type = example.PodConditionType(in.Type)111	out.Status = example.ConditionStatus(in.Status)112	out.LastProbeTime = in.LastProbeTime113	out.LastTransitionTime = in.LastTransitionTime114	out.Reason = in.Reason115	out.Message = in.Message116	return nil117}118// Convert_v1_PodCondition_To_example_PodCondition is an autogenerated conversion function.119func Convert_v1_PodCondition_To_example_PodCondition(in *PodCondition, out *example.PodCondition, s conversion.Scope) error {120	return autoConvert_v1_PodCondition_To_example_PodCondition(in, out, s)121}122func autoConvert_example_PodCondition_To_v1_PodCondition(in *example.PodCondition, out *PodCondition, s conversion.Scope) error {123	out.Type = PodConditionType(in.Type)124	out.Status = ConditionStatus(in.Status)125	out.LastProbeTime = in.LastProbeTime126	out.LastTransitionTime = in.LastTransitionTime127	out.Reason = in.Reason128	out.Message = in.Message129	return nil130}131// Convert_example_PodCondition_To_v1_PodCondition is an autogenerated conversion function.132func Convert_example_PodCondition_To_v1_PodCondition(in *example.PodCondition, out *PodCondition, s conversion.Scope) error {133	return autoConvert_example_PodCondition_To_v1_PodCondition(in, out, s)134}135func autoConvert_v1_PodList_To_example_PodList(in *PodList, out *example.PodList, s conversion.Scope) error {136	out.ListMeta = in.ListMeta137	if in.Items != nil {138		in, out := &in.Items, &out.Items139		*out = make([]example.Pod, len(*in))140		for i := range *in {141			if err := Convert_v1_Pod_To_example_Pod(&(*in)[i], &(*out)[i], s); err != nil {142				return err143			}144		}145	} else {146		out.Items = nil147	}148	return nil149}150// Convert_v1_PodList_To_example_PodList is an autogenerated conversion function.151func Convert_v1_PodList_To_example_PodList(in *PodList, out *example.PodList, s conversion.Scope) error {152	return autoConvert_v1_PodList_To_example_PodList(in, out, s)153}154func autoConvert_example_PodList_To_v1_PodList(in *example.PodList, out *PodList, s conversion.Scope) error {155	out.ListMeta = in.ListMeta156	if in.Items != nil {157		in, out := &in.Items, &out.Items158		*out = make([]Pod, len(*in))159		for i := range *in {160			if err := Convert_example_Pod_To_v1_Pod(&(*in)[i], &(*out)[i], s); err != nil {161				return err162			}163		}164	} else {165		out.Items = nil166	}167	return nil168}169// Convert_example_PodList_To_v1_PodList is an autogenerated conversion function.170func Convert_example_PodList_To_v1_PodList(in *example.PodList, out *PodList, s conversion.Scope) error {171	return autoConvert_example_PodList_To_v1_PodList(in, out, s)172}173func autoConvert_v1_PodSpec_To_example_PodSpec(in *PodSpec, out *example.PodSpec, s conversion.Scope) error {174	out.RestartPolicy = example.RestartPolicy(in.RestartPolicy)175	out.TerminationGracePeriodSeconds = (*int64)(unsafe.Pointer(in.TerminationGracePeriodSeconds))176	out.ActiveDeadlineSeconds = (*int64)(unsafe.Pointer(in.ActiveDeadlineSeconds))177	out.NodeSelector = *(*map[string]string)(unsafe.Pointer(&in.NodeSelector))178	out.ServiceAccountName = in.ServiceAccountName179	// INFO: in.DeprecatedServiceAccount opted out of conversion generation180	out.NodeName = in.NodeName181	// INFO: in.HostNetwork opted out of conversion generation182	// INFO: in.HostPID opted out of conversion generation183	// INFO: in.HostIPC opted out of conversion generation184	out.Hostname = in.Hostname185	out.Subdomain = in.Subdomain186	out.SchedulerName = in.SchedulerName187	return nil188}189// Convert_v1_PodSpec_To_example_PodSpec is an autogenerated conversion function.190func Convert_v1_PodSpec_To_example_PodSpec(in *PodSpec, out *example.PodSpec, s conversion.Scope) error {191	return autoConvert_v1_PodSpec_To_example_PodSpec(in, out, s)192}193func autoConvert_example_PodSpec_To_v1_PodSpec(in *example.PodSpec, out *PodSpec, s conversion.Scope) error {194	out.RestartPolicy = RestartPolicy(in.RestartPolicy)195	out.TerminationGracePeriodSeconds = (*int64)(unsafe.Pointer(in.TerminationGracePeriodSeconds))196	out.ActiveDeadlineSeconds = (*int64)(unsafe.Pointer(in.ActiveDeadlineSeconds))197	out.NodeSelector = *(*map[string]string)(unsafe.Pointer(&in.NodeSelector))198	out.ServiceAccountName = in.ServiceAccountName199	out.NodeName = in.NodeName200	out.Hostname = in.Hostname201	out.Subdomain = in.Subdomain202	out.SchedulerName = in.SchedulerName203	return nil204}205// Convert_example_PodSpec_To_v1_PodSpec is an autogenerated conversion function.206func Convert_example_PodSpec_To_v1_PodSpec(in *example.PodSpec, out *PodSpec, s conversion.Scope) error {207	return autoConvert_example_PodSpec_To_v1_PodSpec(in, out, s)208}209func autoConvert_v1_PodStatus_To_example_PodStatus(in *PodStatus, out *example.PodStatus, s conversion.Scope) error {210	out.Phase = example.PodPhase(in.Phase)211	out.Conditions = *(*[]example.PodCondition)(unsafe.Pointer(&in.Conditions))212	out.Message = in.Message213	out.Reason = in.Reason214	out.HostIP = in.HostIP215	out.PodIP = in.PodIP216	out.StartTime = (*metav1.Time)(unsafe.Pointer(in.StartTime))217	return nil218}219// Convert_v1_PodStatus_To_example_PodStatus is an autogenerated conversion function.220func Convert_v1_PodStatus_To_example_PodStatus(in *PodStatus, out *example.PodStatus, s conversion.Scope) error {221	return autoConvert_v1_PodStatus_To_example_PodStatus(in, out, s)222}223func autoConvert_example_PodStatus_To_v1_PodStatus(in *example.PodStatus, out *PodStatus, s conversion.Scope) error {224	out.Phase = PodPhase(in.Phase)225	out.Conditions = *(*[]PodCondition)(unsafe.Pointer(&in.Conditions))226	out.Message = in.Message227	out.Reason = in.Reason228	out.HostIP = in.HostIP229	out.PodIP = in.PodIP230	out.StartTime = (*metav1.Time)(unsafe.Pointer(in.StartTime))231	return nil232}233// Convert_example_PodStatus_To_v1_PodStatus is an autogenerated conversion function.234func Convert_example_PodStatus_To_v1_PodStatus(in *example.PodStatus, out *PodStatus, s conversion.Scope) error {235	return autoConvert_example_PodStatus_To_v1_PodStatus(in, out, s)236}...World.swift
Source:World.swift  
2/**3    A closure that, when evaluated, returns a dictionary of key-value4    pairs that can be accessed from within a group of shared examples.5*/6public typealias SharedExampleContext = () -> [String: Any]7/**8    A closure that is used to define a group of shared examples. This9    closure may contain any number of example and example groups.10*/11public typealias SharedExampleClosure = (@escaping SharedExampleContext) -> Void12#if canImport(Darwin)13@objcMembers14internal class _WorldBase: NSObject {}15#else16internal class _WorldBase: NSObject {}17#endif18/**19    A collection of state Quick builds up in order to work its magic.20    World is primarily responsible for maintaining a mapping of QuickSpec21    classes to root example groups for those classes.22    It also maintains a mapping of shared example names to shared23    example closures.24    You may configure how Quick behaves by calling the -[World configure:]25    method from within an overridden +[QuickConfiguration configure:] method.26*/27final internal class World: _WorldBase {28    /**29        The example group that is currently being run.30        The DSL requires that this group is correctly set in order to build a31        correct hierarchy of example groups and their examples.32    */33    internal var currentExampleGroup: ExampleGroup!34    /**35        The example metadata of the test that is currently being run.36        This is useful for using the Quick test metadata (like its name) at37        runtime.38    */39    internal var currentExampleMetadata: ExampleMetadata?40    internal var numberOfExamplesRun = 041    /**42        A flag that indicates whether additional test suites are being run43        within this test suite. This is only true within the context of Quick44        functional tests.45    */46#if canImport(Darwin)47    // Convention of generating Objective-C selector has been changed on Swift 348    @objc(isRunningAdditionalSuites)49    internal var isRunningAdditionalSuites = false50#else51    internal var isRunningAdditionalSuites = false52#endif53    private var specs: [String: ExampleGroup] = [:]54    private var sharedExamples: [String: SharedExampleClosure] = [:]55    private let configuration = Configuration()56    internal private(set) var isConfigurationFinalized = false57    internal var exampleHooks: ExampleHooks {return configuration.exampleHooks }58    internal var suiteHooks: SuiteHooks { return configuration.suiteHooks }59    // MARK: Singleton Constructor60    private override init() {}61    static private(set) var sharedWorld = World()62    static func anotherWorld<T>(block: (World) -> T) -> T {63        let previous = sharedWorld64        defer { sharedWorld = previous }65        let newWorld = World()66        sharedWorld = newWorld67        return block(newWorld)68    }69    // MARK: Public Interface70    /**71        Exposes the World's Configuration object within the scope of the closure72        so that it may be configured. This method must not be called outside of73        an overridden +[QuickConfiguration configure:] method.74        - parameter closure:  A closure that takes a Configuration object that can75                         be mutated to change Quick's behavior.76    */77    internal func configure(_ closure: QuickConfigurer) {78        assert(!isConfigurationFinalized,79               "Quick cannot be configured outside of a +[QuickConfiguration configure:] method. You should not call -[World configure:] directly. Instead, subclass QuickConfiguration and override the +[QuickConfiguration configure:] method.")80        closure(configuration)81    }82    /**83        Finalizes the World's configuration.84        Any subsequent calls to World.configure() will raise.85    */86    internal func finalizeConfiguration() {87        isConfigurationFinalized = true88    }89    /**90        Returns an internally constructed root example group for the given91        QuickSpec class.92        A root example group with the description "root example group" is lazily93        initialized for each QuickSpec class. This root example group wraps the94        top level of a -[QuickSpec spec] method--it's thanks to this group that95        users can define beforeEach and it closures at the top level, like so:96            override func spec() {97                // These belong to the root example group98                beforeEach {}99                it("is at the top level") {}100            }101        - parameter specClass: The QuickSpec class for which to retrieve the root example group.102        - returns: The root example group for the class.103    */104    internal func rootExampleGroup(forSpecClass specClass: QuickSpec.Type) -> ExampleGroup {105        let name = String(describing: specClass)106        if let group = specs[name] {107            return group108        } else {109            let group = ExampleGroup(110                description: "root example group",111                flags: [:],112                isInternalRootExampleGroup: true113            )114            specs[name] = group115            return group116        }117    }118    /**119        Returns all examples that should be run for a given spec class.120        There are two filtering passes that occur when determining which examples should be run.121        That is, these examples are the ones that are included by inclusion filters, and are122        not excluded by exclusion filters.123        - parameter specClass: The QuickSpec subclass for which examples are to be returned.124        - returns: A list of examples to be run as test invocations.125    */126    internal func examples(forSpecClass specClass: QuickSpec.Type) -> [Example] {127        // 1. Grab all included examples.128        let included = includedExamples129        // 2. Grab the intersection of (a) examples for this spec, and (b) included examples.130        let spec = rootExampleGroup(forSpecClass: specClass).examples.filter { included.contains($0) }131        // 3. Remove all excluded examples.132        return spec.filter { example in133            !self.configuration.exclusionFilters.contains { $0(example) }134        }135    }136    // MARK: Internal137    internal func registerSharedExample(_ name: String, closure: @escaping SharedExampleClosure) {138        raiseIfSharedExampleAlreadyRegistered(name)139        sharedExamples[name] = closure140    }141    internal func sharedExample(_ name: String) -> SharedExampleClosure {142        raiseIfSharedExampleNotRegistered(name)143        return sharedExamples[name]!144    }145    internal var includedExampleCount: Int {146        return includedExamples.count147    }148    internal lazy var cachedIncludedExampleCount: Int = self.includedExampleCount149    internal var beforesCurrentlyExecuting: Bool {150        let suiteBeforesExecuting = suiteHooks.phase == .beforesExecuting151        let exampleBeforesExecuting = exampleHooks.phase == .beforesExecuting152        var groupBeforesExecuting = false153        if let runningExampleGroup = currentExampleMetadata?.example.group {154            groupBeforesExecuting = runningExampleGroup.phase == .beforesExecuting155        }156        return suiteBeforesExecuting || exampleBeforesExecuting || groupBeforesExecuting157    }158    internal var aftersCurrentlyExecuting: Bool {159        let suiteAftersExecuting = suiteHooks.phase == .aftersExecuting160        let exampleAftersExecuting = exampleHooks.phase == .aftersExecuting161        var groupAftersExecuting = false162        if let runningExampleGroup = currentExampleMetadata?.example.group {163            groupAftersExecuting = runningExampleGroup.phase == .aftersExecuting164        }165        return suiteAftersExecuting || exampleAftersExecuting || groupAftersExecuting166    }167    internal func performWithCurrentExampleGroup(_ group: ExampleGroup, closure: () -> Void) {168        let previousExampleGroup = currentExampleGroup169        currentExampleGroup = group170        closure()171        currentExampleGroup = previousExampleGroup172    }173    private var allExamples: [Example] {174        var all: [Example] = []175        for (_, group) in specs {176            group.walkDownExamples { all.append($0) }177        }178        return all179    }180    private var includedExamples: [Example] {181        let all = allExamples182        let included = all.filter { example in183            return self.configuration.inclusionFilters.contains { $0(example) }184        }185        if included.isEmpty && configuration.runAllWhenEverythingFiltered {186            return all187        } else {188            return included189        }190    }191    private func raiseIfSharedExampleAlreadyRegistered(_ name: String) {192        if sharedExamples[name] != nil {193            raiseError("A shared example named '\(name)' has already been registered.")194        }195    }196    private func raiseIfSharedExampleNotRegistered(_ name: String) {197        if sharedExamples[name] == nil {198            raiseError("No shared example named '\(name)' has been registered. Registered shared examples: '\(Array(sharedExamples.keys))'")199        }200    }201}...Example.swift
Source:Example.swift  
1import Foundation2#if canImport(Darwin)3@objcMembers4public class _ExampleBase: NSObject {}5#else6public class _ExampleBase: NSObject {}7#endif8/**9    Examples, defined with the `it` function, use assertions to10    demonstrate how code should behave. These are like "tests" in XCTest.11*/12final public class Example: _ExampleBase {13    /**14        A boolean indicating whether the example is a shared example;15        i.e.: whether it is an example defined with `itBehavesLike`.16    */17    public var isSharedExample = false18    /**19        The site at which the example is defined.20        This must be set correctly in order for Xcode to highlight21        the correct line in red when reporting a failure.22    */23    public var callsite: Callsite24    weak internal var group: ExampleGroup?25    private let internalDescription: String26    private let closure: () -> Void27    private let flags: FilterFlags28    internal init(description: String, callsite: Callsite, flags: FilterFlags, closure: @escaping () -> Void) {29        self.internalDescription = description30        self.closure = closure31        self.callsite = callsite32        self.flags = flags33    }34    public override var description: String {35        return internalDescription36    }37    /**38        The example name. A name is a concatenation of the name of39        the example group the example belongs to, followed by the40        description of the example itself.41        The example name is used to generate a test method selector42        to be displayed in Xcode's test navigator.43    */44    public var name: String {45        guard let groupName = group?.name else { return description }46        return "\(groupName), \(description)"47    }48    /**49        Executes the example closure, as well as all before and after50        closures defined in the its surrounding example groups.51    */52    public func run() {53        let world = World.sharedWorld54        if world.numberOfExamplesRun == 0 {55            world.suiteHooks.executeBefores()56        }57        let exampleMetadata = ExampleMetadata(example: self, exampleIndex: world.numberOfExamplesRun)58        world.currentExampleMetadata = exampleMetadata59        defer {60            world.currentExampleMetadata = nil61        }62        world.exampleHooks.executeBefores(exampleMetadata)63        group!.phase = .beforesExecuting64        for before in group!.befores {65            before(exampleMetadata)66        }67        group!.phase = .beforesFinished68        closure()69        group!.phase = .aftersExecuting70        for after in group!.afters {71            after(exampleMetadata)72        }73        group!.phase = .aftersFinished74        world.exampleHooks.executeAfters(exampleMetadata)75        world.numberOfExamplesRun += 176        if !world.isRunningAdditionalSuites && world.numberOfExamplesRun >= world.cachedIncludedExampleCount {77            world.suiteHooks.executeAfters()78        }79    }80    /**81        Evaluates the filter flags set on this example and on the example groups82        this example belongs to. Flags set on the example are trumped by flags on83        the example group it belongs to. Flags on inner example groups are trumped84        by flags on outer example groups.85    */86    internal var filterFlags: FilterFlags {87        var aggregateFlags = flags88        for (key, value) in group!.filterFlags {89            aggregateFlags[key] = value90        }91        return aggregateFlags92    }93}94extension Example {95    /**96        Returns a boolean indicating whether two Example objects are equal.97        If two examples are defined at the exact same callsite, they must be equal.98    */99    @nonobjc public static func == (lhs: Example, rhs: Example) -> Bool {100        return lhs.callsite == rhs.callsite101    }102}...runme.go
Source:runme.go  
1// This example illustrates global variable access from Go.2package main3import (4	"./example"5	"fmt"6)7func main() {8	// Try to set the values of some global variables9	example.SetIvar(42)10	example.SetSvar(-31000)11	example.SetLvar(65537)12	example.SetUivar(123456)13	example.SetUsvar(61000)14	example.SetUlvar(654321)15	example.SetScvar(-13)16	example.SetUcvar(251)17	example.SetCvar('S')18	example.SetFvar(3.14159)19	example.SetDvar(2.1828)20	example.SetStrvar("Hello World")21	example.SetIptrvar(example.New_int(37))22	example.SetPtptr(example.New_Point(37, 42))23	example.SetName("Bill")24	// Now print out the values of the variables25	fmt.Println("Variables (values printed from Go)")26	fmt.Println("ivar      =", example.GetIvar())27	fmt.Println("svar      =", example.GetSvar())28	fmt.Println("lvar      =", example.GetLvar())29	fmt.Println("uivar     =", example.GetUivar())30	fmt.Println("usvar     =", example.GetUsvar())31	fmt.Println("ulvar     =", example.GetUlvar())32	fmt.Println("scvar     =", example.GetScvar())33	fmt.Println("ucvar     =", example.GetUcvar())34	fmt.Println("fvar      =", example.GetFvar())35	fmt.Println("dvar      =", example.GetDvar())36	fmt.Printf("cvar      = %c\n", example.GetCvar())37	fmt.Println("strvar    =", example.GetStrvar())38	fmt.Println("cstrvar   =", example.GetCstrvar())39	fmt.Println("iptrvar   =", example.GetIptrvar())40	fmt.Println("name      =", example.GetName())41	fmt.Println("ptptr     =", example.GetPtptr(), example.Point_print(example.GetPtptr()))42	fmt.Println("pt        =", example.GetPt(), example.Point_print(example.GetPt()))43	fmt.Println("\nVariables (values printed from C)")44	example.Print_vars()45	// This line would not compile: since status is marked with46	// %immutable, there is no SetStatus function.47	// fmt.Println("\nNow I'm going to try and modify some read only variables")48	// example.SetStatus(0)49	fmt.Println("\nI'm going to try and update a structure variable.\n")50	example.SetPt(example.GetPtptr())51	fmt.Println("The new value is")52	example.Pt_print()53	fmt.Println("You should see the value", example.Point_print(example.GetPtptr()))54}...Example
Using AI Code Generation
1let example = Example()2let example = Example()3let example = Example()4let example = Example()5let example = Example()6let example = Example()7let example = Example()8let example = Example()9let example = Example()10let example = Example()11let example = Example()12let example = Example()13let example = Example()14let example = Example()15let example = Example()16let example = Example()17let example = Example()18let example = Example()19let example = Example()20let example = Example()21let example = Example()22let example = Example()23let example = Example()Example
Using AI Code Generation
1import Quick2import Nimble3class ExampleSpec: QuickSpec {4    override func spec() {5        describe("Example") {6            it("is working") {7                expect(true).to(beTrue())8            }9        }10    }11}12import Quick13import Nimble14class ExampleSpec: QuickSpec {15    override func spec() {16        describe("Example") {17            it("is working") {18                expect(true).to(beTrue())19            }20        }21    }22}23import Quick24import Nimble25class ExampleSpec: QuickSpec {26    override func spec() {27        describe("Example") {28            it("is working") {29                expect(true).to(beTrue())30            }31        }32    }33}34import Quick35import Nimble36class ExampleSpec: QuickSpec {37    override func spec() {38        describe("Example") {39            it("is working") {40                expect(true).to(beTrue())41            }42        }43    }44}45import Quick46import Nimble47class ExampleSpec: QuickSpec {48    override func spec() {49        describe("Example") {50            it("is working") {51                expect(true).to(beTrue())52            }53        }54    }55}56import Quick57import Nimble58class ExampleSpec: QuickSpec {59    override func spec() {60        describe("Example") {61            it("is working") {62                expect(true).to(beTrue())63            }64        }65    }66}67import Quick68import Nimble69class ExampleSpec: QuickSpec {70    override func spec() {71        describe("Example") {72            it("is working") {73                expect(true).to(beTrue())74            }75        }76    }77}78import Quick79import Nimble80class ExampleSpec: QuickSpec {81    override func spec() {82        describe("Example") {83            it("is working") {84                expect(true).to(beTrue())85            }86        }87    }88}Example
Using AI Code Generation
1let example = Example()2example.printHello()3let example = Example()4example.printHello()5let example = Example()6example.printHello()7let example = Example()8example.printHello()9let example = Example()10example.printHello()11let example = Example()12example.printHello()13let example = Example()14example.printHello()15let example = Example()16example.printHello()17let example = Example()18example.printHello()19let example = Example()20example.printHello()21let example = Example()22example.printHello()23let example = Example()24example.printHello()25let example = Example()26example.printHello()27let example = Example()28example.printHello()29let example = Example()30example.printHello()31let example = Example()32example.printHello()33let example = Example()34example.printHello()35let example = Example()36example.printHello()37let example = Example()38example.printHello()Example
Using AI Code Generation
1import Quick2import Nimble3class ExampleSpec: QuickSpec {4    override func spec() {5        describe("the 'Example' class") {6            it("works") {7                expect(Example().doSomething()) == "something"8            }9        }10    }11}12import Quick13import Nimble14class ExampleSpec: QuickSpec {15    override func spec() {16        describe("the 'Example' class") {17            it("works") {18                expect(Example().doSomething()) == "something"19            }20        }21    }22}23import Quick24import Nimble25class ExampleSpec: QuickSpec {26    override func spec() {27        describe("the 'Example' class") {28            it("works") {29                expect(Example().doSomething()) == "something"30            }31        }32    }33}34import Quick35import Nimble36class ExampleSpec: QuickSpec {37    override func spec() {38        describe("the 'Example' class") {39            it("works") {40                expect(Example().doSomething()) == "something"41            }42        }43    }44}45import Quick46import Nimble47class ExampleSpec: QuickSpec {48    override func spec() {49        describe("the 'Example' class") {50            it("works") {51                expect(Example().doSomething()) == "something"52            }53        }54    }55}56import Quick57import Nimble58class ExampleSpec: QuickSpec {59    override func spec() {60        describe("the 'Example' class") {61            it("works") {62                expect(Example().doSomething()) == "something"63            }64        }65    }66}67import Quick68import Nimble69class ExampleSpec: QuickSpec {70    override func spec() {71        describe("the 'Example' class") {72            it("works") {73                expect(Example().doSomething()) == "something"74            }75        }76    }77}78importExample
Using AI Code Generation
1import Quick2import Nimble3class ExampleSpec: QuickSpec {4    override func spec() {5        describe("an Example") {6            it("works") {7                let example = Example()8                expect(example.value) == 09            }10        }11    }12}13import Quick14import Nimble15class ExampleSpec: QuickSpec {16    override func spec() {17        describe("an Example") {18            it("works") {19                let example = Example()20                expect(example.value) == 021            }22        }23    }24}25import Quick26import Nimble27class ExampleSpec: QuickSpec {28    override func spec() {29        describe("an Example") {30            it("works") {31                let example = Example()32                expect(example.value) == 033            }34        }35    }36}37import Quick38import Nimble39class ExampleSpec: QuickSpec {40    override func spec() {41        describe("an Example") {42            it("works") {43                let example = Example()44                expect(example.value) == 045            }46        }47    }48}49import Quick50import Nimble51class ExampleSpec: QuickSpec {52    override func spec() {53        describe("an Example") {54            it("works") {55                let example = Example()56                expect(example.value) == 057            }58        }59    }60}61import Quick62import Nimble63class ExampleSpec: QuickSpec {64    override func spec() {65        describe("an Example") {66            it("works") {67                let example = Example()68                expect(example.value) == 069            }70        }71    }72}73import Quick74import Nimble75class ExampleSpec: QuickSpec {76    override func spec() {77        describe("an Example") {78            it("works") {79                let example = Example()80                expect(example.value) == 081            }82        }83    }84}85importExample
Using AI Code Generation
1let example = Example()2example.printMessage()3let example = Example()4example.printMessage()5This will generate a file named 2.swiftmodule in the current directory. This file contains the compiled code of the Example class. Now, you can use this file to import the Example class in any Swift file. To import the Example class, use the following code:6import QuickStart7let example = Example()8example.printMessage()9This will generate a file named 3.swiftmodule in the current directory. This file contains the compiled code of the 3.swift file. Now, you can use this file to import the Example class in any Swift file. To import the Example class, use the following code:10import QuickStart11let example = Example()12example.printMessage()13This will generate a file named 4.swiftmodule in the current directory. This file contains the compiled code of the 4.swift file. Now, you can use this file to import the Example class in any Swift file. To import the Example class, use the following code:14import QuickStart15let example = Example()16example.printMessage()17This will generate a file named 5.swiftmodule in the current directory. This file contains the compiled code of the 5.swift file. Now, you can use this file to import the Example class in any Swift file. To import the Example class, use the following code:18import QuickStartExample
Using AI Code Generation
1import Example2import UIKit3class ViewController: UIViewController {4    override func viewDidLoad() {5        super.viewDidLoad()6        let example = Example()7        print(example.hello())8    }9}10import Foundation11public class Example {12    public init() {}13    public func hello() -> String {14    }15}Example
Using AI Code Generation
1import Foundation2let example = Example()3example.quickSort([2, 5, 7, 1, 8, 9, 10, 3, 4, 6])4import Foundation5let example = Example()6example.quickSort([2, 5, 7, 1, 8, 9, 10, 3, 4, 6])7import Foundation8let example = Example()9example.quickSort([2, 5, 7, 1, 8, 9, 10, 3, 4, 6])10import Foundation11let example = Example()12example.quickSort([2, 5, 7, 1, 8, 9, 10, 3, 4, 6])13import Foundation14let example = Example()15example.quickSort([2, 5, 7, 1, 8, 9, 10, 3, 4, 6])16import Foundation17let example = Example()18example.quickSort([2, 5, 7, 1, 8, 9, 10, 3, 4, 6])19import Foundation20let example = Example()21example.quickSort([2, 5, 7, 1, 8, 9, 10, 3, 4, 6])22import Foundation23let example = Example()24example.quickSort([2, 5, 7, 1, 8, 9, 10, 3, 4, 6])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!!
