github.com/saucelabs/saucectl@v0.175.1/internal/playwright/code/parser.go (about)

     1  package code
     2  
     3  import (
     4  	"regexp"
     5  )
     6  
     7  // Functions to parse playwright spec files for testcases.
     8  // The general strategy is to parse in multiple passes; the first pass extracts
     9  // testcase definitions (e.g. it('some test title', { tags: '@tag' }, () => ...)
    10  // and subsequent passes extract the titles.
    11  
    12  var (
    13  	reTestCasePattern = regexp.MustCompile(`(?m)^ *test(?:\.describe)?(\([\s\S]*?,\s*(?:async)?\s*(?:function)?\s*\()`)
    14  	reTitlePattern    = regexp.MustCompile(`\(["'\x60](.*?)["'\x60],\s*?\s*(?:async)?(?:function)?|[{(]`)
    15  )
    16  
    17  // TestCase describes the metadata for a playwright test case parsed from a playwright spec file.
    18  type TestCase struct {
    19  	// Title is the name of the test case, the first argument to `test(.describe)`.
    20  	Title string
    21  }
    22  
    23  // Parse takes the contents of a test file and parses testcases
    24  func Parse(input string) []TestCase {
    25  	matches := reTestCasePattern.FindAllStringSubmatch(input, -1)
    26  
    27  	var testCases []TestCase
    28  	for _, m := range matches {
    29  		tc := TestCase{}
    30  		argSubMatch := m[1]
    31  
    32  		tc.Title = parseTitle(argSubMatch)
    33  
    34  		testCases = append(testCases, tc)
    35  	}
    36  	return testCases
    37  }
    38  
    39  func parseTitle(input string) string {
    40  	titleMatch := reTitlePattern.FindStringSubmatch(input)
    41  	if titleMatch != nil {
    42  		return titleMatch[1]
    43  	}
    44  
    45  	return ""
    46  }