"""
Test the management of tulip.__version__

WARNING: version_test() and possibly other routines in this file will
temporarily replace tulip/commit_hash.txt, if present.  If the test
fails, your tulip installation could be left with a broken version
label.  This comment especially matters for out-of-source testing.
"""

import os
import os.path
import imp


SAMPLE_FILE_TOP = """# DO NOT EDIT!  This file was automatically generated by setup.py of TuLiP
"""
SAMPLE_COMMIT_HASH = """71aefd0659904ccdb8553e5d5f2436933ea42728
"""

def version_test():
    import tulip
    tul_path = os.path.dirname(tulip.__file__)
    filename = os.path.join(tul_path, "commit_hash.txt")
    if os.path.exists(filename):
        commit_hash_backup = open(filename, "r").read()
    else:
        commit_hash_backup = None

    # Release
    with open(filename, "w") as f:
        f.write(SAMPLE_FILE_TOP)

    ver = imp.load_module("version", *imp.find_module("version", [tul_path]))
    assert ver.version == \
        '.'.join([str(x) for x in ver.version_info[:2]])+ver.version_info[2]

    # Dev release
    with open(filename, "a") as f:
        f.write(SAMPLE_COMMIT_HASH)

    ver = imp.load_module("version", *imp.find_module("version", [tul_path]))
    release_str = '.'.join([str(x) for x in ver.version_info[:2]])+ver.version_info[2]
    assert ver.version == release_str+"-dev-"+SAMPLE_COMMIT_HASH.strip()

    # Unknown dev
    os.remove(filename)
    ver = imp.load_module("version", *imp.find_module("version", [tul_path]))
    assert ver.version == release_str+"-dev-unknown-commit"

    # Restore original, if present
    if commit_hash_backup is not None:
        with open(filename, "w") as f:
            f.write(commit_hash_backup)
