Browse Source

symlink: added option 'override'

Fabian Peter Hammerle 8 years ago
parent
commit
6637252e00
2 changed files with 30 additions and 5 deletions
  1. 3 3
      osex/__init__.py
  2. 27 2
      tests/test_symlink.py

+ 3 - 3
osex/__init__.py

@@ -1,10 +1,10 @@
 import os
 
-def symlink(source, link_name, relative = False): #, override = False):
+def symlink(source, link_name, relative = False, override = False):
     if relative:
         source = os.path.relpath(source, os.path.dirname(link_name))
     # os.path.lexists() returns True if path refers to an existing path and 
     # True for broken symbolic links. 
-    # if override and os.path.lexists(link_name):
-    #     os.remove(link_name)
+    if override and os.path.lexists(link_name):
+        os.remove(link_name)
     os.symlink(source, link_name)

+ 27 - 2
tests/test_symlink.py

@@ -3,7 +3,6 @@ import pytest
 import osex
 
 import os
-import sys
 
 def test_new(tmpdir):
     os.chdir(tmpdir.strpath)
@@ -11,7 +10,16 @@ def test_new(tmpdir):
     assert os.path.lexists("link")
     assert os.readlink("link") == "source"
 
-def test_absolute(tmpdir):
+def test_absolute1(tmpdir):
+    os.chdir(tmpdir.strpath)
+    os.makedirs(os.path.join("1", "2"))
+    link = os.path.join("1", "2", "link")
+    source = os.path.join(os.getcwd(), "1", "source")
+    osex.symlink(source, link)
+    assert os.path.lexists(link)
+    assert os.readlink(link) == source
+
+def test_absolute2(tmpdir):
     os.chdir(tmpdir.strpath)
     os.makedirs(os.path.join("1", "2"))
     link = os.path.join("1", "2", "link")
@@ -28,3 +36,20 @@ def test_relative(tmpdir):
     osex.symlink(source, link, relative = True)
     assert os.path.lexists(link)
     assert os.readlink(link) == "../source"
+
+def test_exists(tmpdir):
+    os.chdir(tmpdir.strpath)
+    osex.symlink("source1", "link")
+    assert os.path.lexists("link")
+    with pytest.raises(OSError):
+        osex.symlink("source2", "link")
+    with pytest.raises(OSError):
+        osex.symlink("source3", "link", override = False)
+
+def test_override(tmpdir):
+    os.chdir(tmpdir.strpath)
+    osex.symlink("source1", "link")
+    assert os.path.lexists("link")
+    osex.symlink("source2", "link", override = True)
+    assert os.path.lexists("link")
+    assert os.readlink("link") == "source2"