Skip to content
This repository was archived by the owner on Nov 4, 2024. It is now read-only.

Commit 050eb34

Browse files
author
Mikhail Arkhipov
authored
Port import tests from old LS (microsoft#606)
* Part 8 * Part 9 * Buildable * Part 10 * Part 11 * Part 12 * Buildable * Part 14 * First passing test * Simplify configuration * Style * Fix test and move code to folders * Builtins import * Fix microsoft#470 * Fluents * Add search path * Import analysis, part I * Simplify builtins handling * Remove IMember * Handle import specific * More tests * Add typeshed * Renames * Make sure lazy modules are loaded * Renames * Move/rename * Rework importing * Derivation rework * Part 2 * Part 3 * Buildable * Module members * Async walk * Imports test pass * Remove lazy types * Fix from import * Stubs * Double overloads * Fix datetime test * Couple more tests + fluents * Few more tests * Additionl test + union type * Built-in scrape tests * Full stdlib scrape test * Complete async AST walker * Conditional defines test + variable loc cleanup * More stub tests Fix stub loading for packages (port from DDG) Split walker into multiple files * Add some (broken mostly) tests from DDG * Move document tests * Function arg eval, part I * Instance/factory * Builds * Test fixes * Fix static and instance call eval * More tests * More ported tests * Specialize builtin functions * Make walkers common and handle nested functions * Moar tests * Parser fixes + more tests * Handle negative numbers * Fix null ref * Basic list support * Few more list tests * Basic iterators * Support __iter__ * Iterators * Fix couple of tests * Add decorator test * Generics, part I * Generics, part 2 * Generics, part 3 * Basic TypeVar test * Typings, part 4 * Fix test * Generics, part 6 * Generics, part 7 * More tests (failing) * Forward ref fixes * Reorg * Improve symbol resolution + test fixes * Test fixes * Dictionary, part I * Part 11 * Fix test * Tests * Tests * More dict work * List ctor * Skip some tests for now * Fix iterators * Tuple slicing * Polish type comparo in return types * Add Mapping and tests * Add Iterable * Fix typo * Add Iterator[T] + test * Simplify typing types * Class reduction * Fix tests * Test fix * Handle 'with' statement * Handle try-except * Class method inheritance + NewType * Container types * Containers test * Tests * Handle generic type alias * Named tuple * Global/non-local * Handle tuples in for Handle custom iterators * Basic generator * Any/AnyStr * Test fixes * Type/Optional/etc handling * Proper doc population * Tests + range * Argument match * Basic argset and diagnostics * Argset tests * Exclude WIP * Exclude WIP * Arg eval * Arg match, part 2 * Tests and generic arg comparisons * Function eval with arguments * Baselines * Fix test * Undo AST formatting change and update baseline * LS cleanup 1 * Fix list ctor argument unpacking * Cleanup 2 * Builds * Partial completions * Partial * Partial * Simple test * Tests * Basic startup * Clean up a bit * Remove debug code * Port formatter tests * Fix tokenizer crash * Async fixes * Hover * Basic hover * Adjust expression options * Basic signature help * Fix class/instance * Update test * Fix builtin creation exception * Fix tests * Actually provide declared module * Completion test (partial) * Undo * Fix null await Fix override completions + test * Exports filtering Prevent augmenting imported types * Filter variables & exports * Ported tests * Test fixes * More ported tests * Fix exception completions * Import completions * Scope completions * With completions * Test fixes * WIP * Test fix * Better arg match * Temp disable WIP * First cut * Fix type leak * WIP * Remove ConfigureAwait and handle canceled and failed in the analysis notifications * WIP * Generic class base * Generic forward reference resolution * Suppress completion in strings + test * Prevent recursion on generic resolution Better match arguments * Handle call expression in generics * Relax condition as it happens in tensorflow * Fix typeshed version search Make writing cached modules async Fix module doc fetching * Hover tests * Fix prom import hover * Hover tests * Synchronize test cache writing * First cut * Test * Fixes * Add tests for os.path Null ref fix * Fix cache check * Improve resolution of builtins and typing in stubs * Merge tests * Add ntst for requests * Handle typeshed better * Fix custom stub handling * Better sync * Move files * Fix parameter locations * Hover improvement * PEP hints * One more test for PEP hints * Better handle hover over import as * Text based generic constraints * Handle with better with generic stubs * Undo debug * Handle non-binary open() Temporary fix 'with' handler since we haven't specialized IO/TextIO/BinaryIO yet. * Output syntax errors * Properly clear * - Fix async issue with analysis completion - Clean up diagnostics service interface - Use real DS in tests * Use proper scope when analyzing module * Severity mapping and reporting * Add publishing test Add NSubstitute Move all services to the same namespace. * Unused var * Test forced publish on close * Fix typo * Update test framework * Import location * Remove incorrect reference * Diagnostic severity mapping test Fix post-mortem earlier PR comment * Minor fixes * Move interface to the main class part * Flicker reduction * - Correct reported unresolved import name - Add tests * PR feedback * Port 2 tests * More tests * More tests * Fix typing and package import test * Last test * Call base instead
1 parent 6c86149 commit 050eb34

File tree

8 files changed

+348
-28
lines changed

8 files changed

+348
-28
lines changed

src/Analysis/Ast/Impl/Modules/Definitions/IModuleResolution.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// See the Apache Version 2.0 License for specific language governing
1414
// permissions and limitations under the License.
1515

16+
using System.Collections.Generic;
1617
using System.Threading;
1718
using System.Threading.Tasks;
1819
using Microsoft.Python.Analysis.Core.DependencyResolution;
@@ -50,6 +51,12 @@ public interface IModuleResolution {
5051
/// </summary>
5152
IPythonModule GetImportedModule(string name);
5253

54+
/// <summary>
55+
/// Sets user search paths. This changes <see cref="CurrentPathResolver"/>.
56+
/// </summary>
57+
/// <returns>Added roots.</returns>
58+
IEnumerable<string> SetUserSearchPaths(in IEnumerable<string> searchPaths);
59+
5360
Task ReloadAsync(CancellationToken token = default);
5461
}
5562
}

src/Analysis/Ast/Impl/Modules/Resolution/MainModuleResolution.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -147,25 +147,25 @@ internal async Task LoadBuiltinTypesAsync(CancellationToken cancellationToken =
147147
var builtinModuleNamesMember = BuiltinsModule.GetAnyMember("__builtin_module_names__");
148148
if (builtinModuleNamesMember.TryGetConstant<string>(out var s)) {
149149
var builtinModuleNames = s.Split(',').Select(n => n.Trim());
150-
_pathResolver.SetBuiltins(builtinModuleNames);
150+
PathResolver.SetBuiltins(builtinModuleNames);
151151
}
152152
}
153153

154154
public override async Task ReloadAsync(CancellationToken cancellationToken = default) {
155155
ModuleCache = new ModuleCache(_interpreter, _services);
156156

157-
_pathResolver = new PathResolver(_interpreter.LanguageVersion);
157+
PathResolver = new PathResolver(_interpreter.LanguageVersion);
158158

159-
var addedRoots = _pathResolver.SetRoot(_root);
159+
var addedRoots = PathResolver.SetRoot(_root);
160160
ReloadModulePaths(addedRoots);
161161

162162
var interpreterPaths = await GetSearchPathsAsync(cancellationToken);
163-
addedRoots = _pathResolver.SetInterpreterSearchPaths(interpreterPaths);
163+
addedRoots = PathResolver.SetInterpreterSearchPaths(interpreterPaths);
164164

165165
ReloadModulePaths(addedRoots);
166166
cancellationToken.ThrowIfCancellationRequested();
167167

168-
addedRoots = _pathResolver.SetUserSearchPaths(_interpreter.Configuration.SearchPaths);
168+
addedRoots = SetUserSearchPaths(_interpreter.Configuration.SearchPaths);
169169
ReloadModulePaths(addedRoots);
170170
}
171171

src/Analysis/Ast/Impl/Modules/Resolution/ModuleResolutionBase.cs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ internal abstract class ModuleResolutionBase {
3838
protected readonly bool _requireInitPy;
3939
protected string _root;
4040

41-
protected PathResolver _pathResolver;
41+
protected PathResolver PathResolver { get; set; }
4242

4343
protected InterpreterConfiguration Configuration => _interpreter.Configuration;
4444

@@ -58,7 +58,7 @@ protected ModuleResolutionBase(string root, IServiceContainer services) {
5858
/// <summary>
5959
/// Path resolver providing file resolution in module imports.
6060
/// </summary>
61-
public PathResolverSnapshot CurrentPathResolver => _pathResolver.CurrentSnapshot;
61+
public PathResolverSnapshot CurrentPathResolver => PathResolver.CurrentSnapshot;
6262

6363
/// <summary>
6464
/// Builtins module.
@@ -68,7 +68,7 @@ protected ModuleResolutionBase(string root, IServiceContainer services) {
6868
public abstract Task ReloadAsync(CancellationToken cancellationToken = default);
6969
protected abstract Task<IPythonModule> DoImportAsync(string name, CancellationToken cancellationToken = default);
7070

71-
public IReadOnlyCollection<string> GetPackagesFromDirectory(string searchPath, CancellationToken cancellationToken) {
71+
public IReadOnlyCollection<string> GetPackagesFromDirectory(string searchPath, CancellationToken cancellationToken) {
7272
return ModulePath.GetModulesInPath(
7373
searchPath,
7474
recurse: false,
@@ -77,10 +77,18 @@ public IReadOnlyCollection<string> GetPackagesFromDirectory(string searchPath, C
7777
).Select(mp => mp.ModuleName).Where(n => !string.IsNullOrEmpty(n)).TakeWhile(_ => !cancellationToken.IsCancellationRequested).ToList();
7878
}
7979

80-
public IPythonModule GetImportedModule(string name)
81-
=> _modules.TryGetValue(name, out var module) ? module : null;
80+
public IPythonModule GetImportedModule(string name) {
81+
var module = _interpreter.ModuleResolution.GetSpecializedModule(name);
82+
if (module != null) {
83+
return module;
84+
}
85+
return _modules.TryGetValue(name, out module) ? module : null;
86+
}
87+
88+
public IEnumerable<string> SetUserSearchPaths(in IEnumerable<string> searchPaths)
89+
=> PathResolver.SetUserSearchPaths(searchPaths);
8290

83-
public void AddModulePath(string path) => _pathResolver.TryAddModulePath(path, out var _);
91+
public void AddModulePath(string path) => PathResolver.TryAddModulePath(path, out var _);
8492

8593
public ModulePath FindModule(string filePath) {
8694
var bestLibraryPath = string.Empty;
@@ -207,7 +215,7 @@ private async Task<TryImportModuleResult> TryImportModuleAsync(string name, Canc
207215

208216
protected void ReloadModulePaths(in IEnumerable<string> rootPaths) {
209217
foreach (var modulePath in rootPaths.Where(Directory.Exists).SelectMany(p => PathUtils.EnumerateFiles(p))) {
210-
_pathResolver.TryAddModulePath(modulePath, out _);
218+
PathResolver.TryAddModulePath(modulePath, out _);
211219
}
212220
}
213221

src/Analysis/Ast/Impl/Modules/Resolution/TypeshedResolution.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,12 +65,12 @@ protected override async Task<IPythonModule> DoImportAsync(string name, Cancella
6565
}
6666

6767
public override Task ReloadAsync(CancellationToken cancellationToken = default) {
68-
_pathResolver = new PathResolver(_interpreter.LanguageVersion);
68+
PathResolver = new PathResolver(_interpreter.LanguageVersion);
6969

70-
var addedRoots = _pathResolver.SetRoot(_root);
70+
var addedRoots = PathResolver.SetRoot(_root);
7171
ReloadModulePaths(addedRoots);
7272

73-
addedRoots = _pathResolver.SetInterpreterSearchPaths(_typeStubPaths);
73+
addedRoots = PathResolver.SetInterpreterSearchPaths(_typeStubPaths);
7474
ReloadModulePaths(addedRoots);
7575

7676
cancellationToken.ThrowIfCancellationRequested();

src/Analysis/Ast/Test/AnalysisTestBase.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,12 @@ protected async Task<IServiceManager> CreateServicesAsync(string root, Interpret
100100
return sm;
101101
}
102102

103+
protected async Task CreateServicesAsync(InterpreterConfiguration configuration, string modulePath) {
104+
modulePath = modulePath ?? TestData.GetDefaultModulePath();
105+
var moduleDirectory = Path.GetDirectoryName(modulePath);
106+
await CreateServicesAsync(moduleDirectory, configuration);
107+
}
108+
103109
protected Task<IDocumentAnalysis> GetAnalysisAsync(string code, PythonLanguageVersion version, string modulePath = null)
104110
=> GetAnalysisAsync(code, PythonVersions.GetRequiredCPythonConfiguration(version), modulePath);
105111

@@ -129,7 +135,7 @@ protected async Task<IDocumentAnalysis> GetAnalysisAsync(
129135
string modulePath = null) {
130136

131137
var moduleUri = modulePath != null ? new Uri(modulePath) : TestData.GetDefaultModuleUri();
132-
modulePath = modulePath ?? TestData .GetDefaultModulePath();
138+
modulePath = modulePath ?? TestData.GetDefaultModulePath();
133139
moduleName = moduleName ?? Path.GetFileNameWithoutExtension(modulePath);
134140

135141
IDocument doc;

src/LanguageServer/Impl/Completion/ImportCompletion.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,6 @@ private static CompletionResult GetResultFromSearch(IImportSearchResult importSe
150150
break;
151151
case PackageImport packageImports:
152152
return new CompletionResult(packageImports.Modules
153-
.Select(m => mres.GetImportedModule(m.FullName))
154-
.ExcludeDefault()
155153
.Select(m => CompletionItemSource.CreateCompletionItem(m.Name, CompletionItemKind.Module))
156154
.Prepend(CompletionItemSource.Star));
157155
default:

src/LanguageServer/Test/CompletionTests.cs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,8 @@ def method(self):
5555
";
5656
var analysis = await GetAnalysisAsync(code);
5757
var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
58-
var comps = (await cs.GetCompletionsAsync(analysis, new SourceLocation(8, 1))).Completions.ToArray();
59-
comps.Select(c => c.label).Should().Contain("C", "x", "y", "while", "for", "yield");
58+
var comps = await cs.GetCompletionsAsync(analysis, new SourceLocation(8, 1));
59+
comps.Should().HaveLabels("C", "x", "y", "while", "for", "yield");
6060
}
6161

6262
[TestMethod, Priority(0)]
@@ -67,8 +67,8 @@ public async Task StringMembers() {
6767
";
6868
var analysis = await GetAnalysisAsync(code);
6969
var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
70-
var comps = (await cs.GetCompletionsAsync(analysis, new SourceLocation(3, 3))).Completions.ToArray();
71-
comps.Select(c => c.label).Should().Contain(new[] { @"isupper", @"capitalize", @"split" });
70+
var comps = await cs.GetCompletionsAsync(analysis, new SourceLocation(3, 3));
71+
comps.Should().HaveLabels(@"isupper", @"capitalize", @"split" );
7272
}
7373

7474
[TestMethod, Priority(0)]
@@ -79,8 +79,8 @@ import datetime
7979
";
8080
var analysis = await GetAnalysisAsync(code);
8181
var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
82-
var comps = (await cs.GetCompletionsAsync(analysis, new SourceLocation(3, 19))).Completions.ToArray();
83-
comps.Select(c => c.label).Should().Contain(new[] { "now", @"tzinfo", @"ctime" });
82+
var comps = await cs.GetCompletionsAsync(analysis, new SourceLocation(3, 19));
83+
comps.Should().HaveLabels("now", @"tzinfo", @"ctime");
8484
}
8585

8686
[TestMethod, Priority(0)]
@@ -94,11 +94,11 @@ def method1(self): pass
9494
";
9595
var analysis = await GetAnalysisAsync(code);
9696
var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
97-
var comps = (await cs.GetCompletionsAsync(analysis, new SourceLocation(5, 4))).Completions.ToArray();
98-
comps.Select(c => c.label).Should().Contain(@"ABCDE");
97+
var comps = await cs.GetCompletionsAsync(analysis, new SourceLocation(5, 4));
98+
comps.Should().HaveLabels(@"ABCDE");
9999

100-
comps = (await cs.GetCompletionsAsync(analysis, new SourceLocation(6, 9))).Completions.ToArray();
101-
comps.Select(c => c.label).Should().Contain("method1");
100+
comps = await cs.GetCompletionsAsync(analysis, new SourceLocation(6, 9));
101+
comps.Should().HaveLabels("method1");
102102
}
103103

104104
[DataRow(PythonLanguageVersion.V36, "value")]

0 commit comments

Comments
 (0)