dissolve-python 0.3.0

A tool to dissolve deprecated calls in Python codebases
Documentation
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
// Copyright (C) 2024 Jelmer Vernooij <jelmer@samba.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::dependency_collector::{
    clear_module_cache, collect_deprecated_from_dependencies_with_paths,
};
use crate::migrate_ruff;
use crate::TypeIntrospectionMethod;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use tempfile::TempDir;

/// Helper to create a Python module file
fn create_module(dir: &std::path::Path, rel_path: &str, content: &str) -> PathBuf {
    let full_path = dir.join(rel_path);
    if let Some(parent) = full_path.parent() {
        fs::create_dir_all(parent).unwrap();
    }
    fs::write(&full_path, content).unwrap();
    full_path
}

#[test]
fn test_simple_function_cross_module() {
    // Clear module cache to ensure test isolation
    clear_module_cache();

    let temp_dir = TempDir::new().unwrap();

    // Create deprecated module
    let deprecated_module = r#"
from dissolve import replace_me

@replace_me()
def old_function(x, y):
    return new_function(x, y)

def new_function(x, y):
    return x + y
"#;

    // Create module that uses the deprecated function
    let user_module = r#"
from testpkg.deprecated import old_function

def test():
    result = old_function(1, 2)
    return result
"#;

    // Create the files
    create_module(temp_dir.path(), "testpkg/__init__.py", "");
    create_module(temp_dir.path(), "testpkg/deprecated.py", deprecated_module);
    let user_path = create_module(temp_dir.path(), "testpkg/user.py", user_module);

    // Create pyrightconfig.json to help Pyright find modules
    let pyright_config = r#"{
        "include": ["testpkg"],
        "pythonVersion": "3.8",
        "pythonPlatform": "All",
        "typeCheckingMode": "basic",
        "useLibraryCodeForTypes": true
    }"#;
    fs::write(temp_dir.path().join("pyrightconfig.json"), pyright_config).unwrap();

    // Collect deprecations from the user module with temp directory in search path
    let additional_paths = vec![temp_dir.path().to_string_lossy().to_string()];
    let dep_result = collect_deprecated_from_dependencies_with_paths(
        user_module,
        "testpkg.user",
        5,
        &additional_paths,
    )
    .unwrap();

    // Should find the deprecated function
    assert!(dep_result
        .replacements
        .contains_key("testpkg.deprecated.old_function"));

    // Create type introspection context with temp directory as workspace
    let mut type_context = crate::tests::test_utils::create_test_type_context_with_workspace(
        TypeIntrospectionMethod::PyrightLsp,
        temp_dir.path().to_str().unwrap(),
    );

    // Open the package files in Pyright so it knows about the module structure
    type_context
        .open_file(&temp_dir.path().join("testpkg/__init__.py"), "")
        .unwrap();
    type_context
        .open_file(
            &temp_dir.path().join("testpkg/deprecated.py"),
            deprecated_module,
        )
        .unwrap();

    // Migrate the user module
    let result = migrate_ruff::migrate_file(
        user_module,
        "testpkg.user",
        &user_path,
        &mut type_context,
        dep_result.replacements,
        dep_result.inheritance_map,
    )
    .unwrap();

    type_context.shutdown().unwrap();

    // Check the result

    // When the function is imported but the replacement is in the same module,
    // we need to also import the new function
    assert!(result.contains("from testpkg.deprecated import"));

    // The replacement should now work with import tracking
    assert!(result.contains("new_function(1, 2)"));
    assert!(!result.contains("old_function(1, 2)"));
}

#[test]
fn test_class_method_cross_module() {
    // Clear module cache to ensure test isolation
    clear_module_cache();

    let temp_dir = TempDir::new().unwrap();

    // Create module with deprecated class
    let deprecated_module = r#"
from dissolve import replace_me

class OldAPI:
    @replace_me()
    def old_method(self, data):
        return self.new_method(data)
        
    def new_method(self, data):
        return data
"#;

    // Create module that uses the deprecated method
    let user_module = r#"
from testpkg.api import OldAPI

def process():
    api = OldAPI()
    api.old_method("test")
    
def process_with_variable():
    api = OldAPI()
    obj = api
    obj.old_method("data")
"#;

    // Create the files
    create_module(temp_dir.path(), "testpkg/__init__.py", "");
    create_module(temp_dir.path(), "testpkg/api.py", deprecated_module);
    let client_path = create_module(temp_dir.path(), "testpkg/client.py", user_module);

    // Collect deprecations from dependencies with temp directory in search path
    let additional_paths = vec![temp_dir.path().to_string_lossy().to_string()];
    let dep_result = collect_deprecated_from_dependencies_with_paths(
        user_module,
        "testpkg.client",
        5,
        &additional_paths,
    )
    .unwrap();

    // Should find the deprecated method
    assert!(dep_result
        .replacements
        .contains_key("testpkg.api.OldAPI.old_method"));

    // Create type introspection context with temp directory as workspace
    let mut type_context = crate::tests::test_utils::create_test_type_context_with_workspace(
        TypeIntrospectionMethod::PyrightLsp,
        temp_dir.path().to_str().unwrap(),
    );

    // Migrate the client module
    let result = migrate_ruff::migrate_file(
        user_module,
        "testpkg.client",
        &client_path,
        &mut type_context,
        dep_result.replacements,
        dep_result.inheritance_map,
    )
    .unwrap();

    type_context.shutdown().unwrap();

    // Both calls should be replaced
    if !result.contains("api.new_method(\"test\")") {
        eprintln!("Expected api.new_method(\"test\"), but got:");
        eprintln!("{}", result);
    }
    assert!(result.contains("api.new_method(\"test\")"));
    assert!(result.contains("obj.new_method(\"data\")"));
    assert!(!result.contains("old_method"));
}

#[test]
fn test_classmethod_cross_module() {
    // Clear module cache to ensure test isolation
    clear_module_cache();

    let temp_dir = TempDir::new().unwrap();

    let deprecated_module = r#"
from dissolve import replace_me

class Factory:
    @classmethod
    @replace_me()
    def old_create(cls, name):
        return cls.new_create(name)
        
    @classmethod
    def new_create(cls, name):
        return cls(name)
"#;

    let user_module = r#"
from testpkg.factory import Factory

def create_instance():
    return Factory.old_create("test")
"#;

    // Create the files
    create_module(temp_dir.path(), "testpkg/__init__.py", "");
    create_module(temp_dir.path(), "testpkg/factory.py", deprecated_module);
    let user_path = create_module(temp_dir.path(), "testpkg/user.py", user_module);

    // Create pyrightconfig.json to help Pyright find modules
    let pyright_config = r#"{
        "include": ["testpkg"],
        "pythonVersion": "3.8",
        "pythonPlatform": "All",
        "typeCheckingMode": "basic",
        "useLibraryCodeForTypes": true
    }"#;
    fs::write(temp_dir.path().join("pyrightconfig.json"), pyright_config).unwrap();

    // Collect deprecations from dependencies with temp directory in search path
    let additional_paths = vec![temp_dir.path().to_string_lossy().to_string()];
    let dep_result = collect_deprecated_from_dependencies_with_paths(
        user_module,
        "testpkg.user",
        5,
        &additional_paths,
    )
    .unwrap();

    // Should find the deprecated classmethod
    assert!(dep_result
        .replacements
        .contains_key("testpkg.factory.Factory.old_create"));

    // Create type introspection context with temp directory as workspace
    let mut type_context = crate::tests::test_utils::create_test_type_context_with_workspace(
        TypeIntrospectionMethod::PyrightLsp,
        temp_dir.path().to_str().unwrap(),
    );

    // Open the package files in Pyright so it knows about the module structure
    type_context
        .open_file(&temp_dir.path().join("testpkg/__init__.py"), "")
        .unwrap();
    type_context
        .open_file(
            &temp_dir.path().join("testpkg/factory.py"),
            deprecated_module,
        )
        .unwrap();

    // Migrate
    let result = migrate_ruff::migrate_file(
        user_module,
        "testpkg.user",
        &user_path,
        &mut type_context,
        dep_result.replacements,
        dep_result.inheritance_map,
    )
    .unwrap();

    type_context.shutdown().unwrap();

    assert!(result.contains("Factory.new_create(\"test\")"));
    assert!(!result.contains("old_create"));
}

#[test]
fn test_staticmethod_cross_module() {
    // Clear module cache to ensure test isolation
    clear_module_cache();

    let temp_dir = TempDir::new().unwrap();

    let deprecated_module = r#"
from dissolve import replace_me

class Utils:
    @staticmethod
    @replace_me()
    def old_helper(x):
        return new_helper(x)

def new_helper(x):
    return x * 2
"#;

    let user_module = r#"
from testpkg.utils import Utils

def calculate():
    return Utils.old_helper(5)
"#;

    // Create the files
    create_module(temp_dir.path(), "testpkg/__init__.py", "");
    create_module(temp_dir.path(), "testpkg/utils.py", deprecated_module);
    let user_path = create_module(temp_dir.path(), "testpkg/user.py", user_module);

    // Collect deprecations from dependencies with temp directory in search path
    let additional_paths = vec![temp_dir.path().to_string_lossy().to_string()];
    let dep_result = collect_deprecated_from_dependencies_with_paths(
        user_module,
        "testpkg.user",
        5,
        &additional_paths,
    )
    .unwrap();

    // Should find the deprecated staticmethod
    assert!(dep_result
        .replacements
        .contains_key("testpkg.utils.Utils.old_helper"));

    // Create type introspection context with temp directory as workspace
    let mut type_context = crate::tests::test_utils::create_test_type_context_with_workspace(
        TypeIntrospectionMethod::PyrightLsp,
        temp_dir.path().to_str().unwrap(),
    );

    // Open the dependency file in Pyright so it knows about the Utils class
    type_context
        .open_file(&temp_dir.path().join("testpkg/utils.py"), deprecated_module)
        .unwrap();

    // Migrate
    let result = migrate_ruff::migrate_file(
        user_module,
        "testpkg.user",
        &user_path,
        &mut type_context,
        dep_result.replacements,
        dep_result.inheritance_map,
    )
    .unwrap();

    type_context.shutdown().unwrap();

    assert!(result.contains("new_helper(5)"));
    assert!(!result.contains("old_helper"));
}

#[test]
fn test_import_alias() {
    // Clear module cache to ensure test isolation
    clear_module_cache();

    let temp_dir = TempDir::new().unwrap();

    let deprecated_module = r#"
from dissolve import replace_me

@replace_me()
def old_function(x):
    return new_function(x)

def new_function(x):
    return x * 2
"#;

    let user_module = r#"
from testpkg.deprecated import old_function as legacy_func

def test():
    return legacy_func(42)
"#;

    // Create the files
    create_module(temp_dir.path(), "testpkg/__init__.py", "");
    create_module(temp_dir.path(), "testpkg/deprecated.py", deprecated_module);
    let user_path = create_module(temp_dir.path(), "testpkg/user.py", user_module);

    // Collect deprecations from dependencies with temp directory in search path
    let additional_paths = vec![temp_dir.path().to_string_lossy().to_string()];
    let dep_result = collect_deprecated_from_dependencies_with_paths(
        user_module,
        "testpkg.user",
        5,
        &additional_paths,
    )
    .unwrap();

    // Should find the deprecated function even with alias
    assert!(dep_result
        .replacements
        .contains_key("testpkg.deprecated.old_function"));

    println!(
        "Replacements found: {:?}",
        dep_result.replacements.keys().collect::<Vec<_>>()
    );

    // Create type introspection context with temp directory as workspace
    let mut type_context = crate::tests::test_utils::create_test_type_context_with_workspace(
        TypeIntrospectionMethod::PyrightLsp,
        temp_dir.path().to_str().unwrap(),
    );

    // Migrate
    let result = migrate_ruff::migrate_file(
        user_module,
        "testpkg.user",
        &user_path,
        &mut type_context,
        dep_result.replacements,
        dep_result.inheritance_map,
    )
    .unwrap();

    type_context.shutdown().unwrap();

    // Our current implementation doesn't track import aliases
    // so legacy_func calls won't be replaced
    if !result.contains("legacy_func(42)") {
        eprintln!("Expected legacy_func(42) to remain unchanged, but got:");
        eprintln!("{}", result);
    }
    assert!(result.contains("legacy_func(42)"));
    assert!(result.contains("from testpkg.deprecated import old_function as legacy_func"));
}

#[test]
fn test_with_statement_context_manager() {
    // Clear module cache to ensure test isolation
    clear_module_cache();

    let temp_dir = TempDir::new().unwrap();

    let deprecated_module = r#"
from dissolve import replace_me

class Resource:
    @replace_me()
    def old_close(self):
        return self.new_close()
        
    def new_close(self):
        pass
        
    def __enter__(self):
        return self
        
    def __exit__(self, *args):
        pass
"#;

    let user_module = r#"
from testpkg.resource import Resource

def use_resource():
    with Resource() as res:
        # do something
        res.old_close()
"#;

    // Create the files
    create_module(temp_dir.path(), "testpkg/__init__.py", "");
    create_module(temp_dir.path(), "testpkg/resource.py", deprecated_module);
    let user_path = create_module(temp_dir.path(), "testpkg/user.py", user_module);

    // Collect deprecations from dependencies with temp directory in search path
    let additional_paths = vec![temp_dir.path().to_string_lossy().to_string()];
    let dep_result = collect_deprecated_from_dependencies_with_paths(
        user_module,
        "testpkg.user",
        5,
        &additional_paths,
    )
    .unwrap();

    // Should find the deprecated method
    assert!(dep_result
        .replacements
        .contains_key("testpkg.resource.Resource.old_close"));

    // Create type introspection context with temp directory as workspace
    let mut type_context = crate::tests::test_utils::create_test_type_context_with_workspace(
        TypeIntrospectionMethod::PyrightLsp,
        temp_dir.path().to_str().unwrap(),
    );

    // Migrate
    let result = migrate_ruff::migrate_file(
        user_module,
        "testpkg.user",
        &user_path,
        &mut type_context,
        dep_result.replacements,
        dep_result.inheritance_map,
    )
    .unwrap();

    type_context.shutdown().unwrap();

    assert!(result.contains("res.new_close()"));
    assert!(!result.contains("old_close"));
}

#[test]
fn test_scan_dependencies_disabled() {
    // Clear module cache to ensure test isolation
    clear_module_cache();

    // Test with dependency scanning disabled - the function shouldn't be replaced
    let source = r#"
from testpkg.api import old_function

def test():
    old_function()
"#;

    // Create test context and type introspection context
    let test_ctx = crate::tests::test_utils::TestContext::new(source);
    let mut type_context = test_ctx.create_type_context(TypeIntrospectionMethod::PyrightLsp);

    // Migrate with empty replacements (simulating no dependency scanning)
    let result = migrate_ruff::migrate_file(
        source,
        "testmodule",
        Path::new(&test_ctx.file_path),
        &mut type_context,
        HashMap::new(),
        HashMap::new(),
    )
    .unwrap();

    type_context.shutdown().unwrap();

    // Should not change since we didn't provide any replacements
    assert!(result.contains("old_function()"));
}