File: TestSwiftPlaygrounds.py

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (200 lines) | stat: -rw-r--r-- 7,427 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# TestPlaygrounds.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
"""
Test that playgrounds work
"""
import subprocess
import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
import lldbsuite.test.lldbutil as lldbutil
import os
import os.path
import platform
import unittest2
from lldbsuite.test.builders.darwin import get_triple

import sys
if sys.version_info.major == 2:
    import commands as subprocess
else:
    import subprocess


def execute_command(command):
    (exit_status, output) = subprocess.getstatusoutput(command)
    return exit_status


class TestSwiftPlaygrounds(TestBase):
    def get_build_triple(self):
        """We want to build the file with a deployment target earlier than the
           availability set in the source file."""
        if lldb.remote_platform:
            arch = self.getArchitecture()
            vendor, os, version, _ = get_triple()
            # This is made slightly more complex by watchOS having misaligned
            # version numbers.
            if os == 'watchos':
                version = '5.0'
            else:
                version = '7.0'
            triple = '{}-{}-{}{}'.format(arch, vendor, os, version)
        else:
            triple = '{}-apple-macosx11.0'.format(platform.machine())
        return triple

    def get_run_triple(self):
        if lldb.remote_platform:
            arch = self.getArchitecture()
            vendor, os, version, _ = get_triple()
            triple = '{}-{}-{}{}'.format(arch, vendor, os, version)
        else:
            version, _, machine = platform.mac_ver()
            triple = '{}-apple-macosx{}'.format(machine, version)
        return triple

    @skipUnlessDarwin
    @swiftTest
    @skipIf(setting=('symbols.use-swift-clangimporter', 'false'))
    @skipIf(debug_info=decorators.no_match("dsym"))
    def test_force_target(self):
        """Test that playgrounds work"""
        self.launch(True)
        self.do_basic_test(True)

    @skipUnlessDarwin
    @swiftTest
    @skipIf(setting=('symbols.use-swift-clangimporter', 'false'))
    @skipIf(debug_info=decorators.no_match("dsym"))
    def test_no_force_target(self):
        """Test that playgrounds work"""
        self.launch(False)
        self.do_basic_test(False)

    @skipUnlessDarwin
    @swiftTest
    @skipIf(setting=('symbols.use-swift-clangimporter', 'false'))
    @skipIf(debug_info=decorators.no_match("dsym"))
    @skipIf(macos_version=["<", "12"])
    def test_concurrency(self):
        """Test that concurrency is available in playgrounds"""
        self.launch(True)
        self.do_concurrency_test()

    @skipUnlessDarwin
    @swiftTest
    @skipIf(setting=('symbols.use-swift-clangimporter', 'false'))
    @skipIf(debug_info=decorators.no_match("dsym"))
    def test_import(self):
        """Test that a dylib can be imported in playgrounds"""
        self.launch(True)
        self.do_import_test()
        
    def launch(self, force_target):
        """Test that playgrounds work"""
        self.build(dictionary={
            'TARGET_SWIFTFLAGS':
            '-target {}'.format(self.get_build_triple()),
        })

        # Create the target
        exe = self.getBuildArtifact("PlaygroundStub")
        if force_target:
            target = self.dbg.CreateTargetWithFileAndArch(
                exe, self.get_run_triple())
        else:
            target = self.dbg.CreateTarget(exe)

        self.assertTrue(target, VALID_TARGET)
        self.registerSharedLibrariesWithTarget(target,
                                               ['libPlaygroundsRuntime.dylib'])

        # Set the breakpoints
        breakpoint = target.BreakpointCreateBySourceRegex(
            'Set breakpoint here', lldb.SBFileSpec("PlaygroundStub.swift"))
        self.assertTrue(breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT)

        process = target.LaunchSimple(None, None, os.getcwd())
        self.assertTrue(process, PROCESS_IS_VALID)

        threads = lldbutil.get_threads_stopped_at_breakpoint(
            process, breakpoint)

        self.assertEqual(len(threads), 1)
        self.expect('settings set target.swift-framework-search-paths "%s"' %
                    self.getBuildDir())

    def execute_code(self, input_file, expect_error=False):
        contents = "syntax error"
        with open(input_file, 'r') as contents_file:
            contents = contents_file.read()

        options = lldb.SBExpressionOptions()
        options.SetLanguage(lldb.eLanguageTypeSwift)
        options.SetPlaygroundTransformEnabled()
        # The concurrency expressions will spawn multiple threads.
        options.SetOneThreadTimeoutInMicroSeconds(1)
        options.SetTryAllThreads(True)
        options.SetAutoApplyFixIts(False)

        res = self.frame().EvaluateExpression(contents, options)
        ret = self.frame().EvaluateExpression("get_output()")
        is_error = res.GetError().Fail() and not (
                     res.GetError().GetType() == 1 and
                     res.GetError().GetError() == 0x1001)
        playground_output = ret.GetSummary()
        with recording(self, self.TraceOn()) as sbuf:
            print("playground result: ", file=sbuf)
            print(str(res), file=sbuf)
            if is_error:
                print("error:", file=sbuf)
                print(str(res.GetError()), file=sbuf)
            else:
                print("playground output:", file=sbuf)
                print(str(ret), file=sbuf)

        if expect_error:
            self.assertTrue(is_error)
            return playground_output
        self.assertFalse(is_error)
        self.assertIsNotNone(playground_output)
        return playground_output
        
    def do_basic_test(self, force_target):
        playground_output = self.execute_code('Contents.swift', not force_target)
        if not force_target:
            # This is expected to fail because the deployment target
            # is less than the availability of the function being
            # called.
            self.assertEqual(playground_output, '""')
            return

        self.assertIn("a=\\'3\\'", playground_output)
        self.assertIn("b=\\'5\\'", playground_output)
        self.assertIn("=\\'8\\'", playground_output)
        self.assertIn("=\\'11\\'", playground_output)

    def do_concurrency_test(self):
        playground_output = self.execute_code('Concurrency.swift')
        self.assertIn("=\\'23\\'", playground_output)

    def do_import_test(self):
        # Test importing a library that adds new Clang options.
        log = self.getBuildArtifact('types.log')
        self.expect('log enable lldb types -f ' + log)
        playground_output = self.execute_code('Import.swift')
        self.assertIn("Hello from the Dylib", playground_output)

        # Scan through the types log to make sure the SwiftASTContext was poisoned.
        self.filecheck('platform shell cat ""%s"' % log, __file__)
#       CHECK: New Swift image added{{.*}}Versions/A/Dylib{{.*}}ClangImporter needs to be reinitialized