| 79 | |
| 80 | |
| 81 | class EnvironmentVariableTest(unittest.TestCase): |
| 82 | """ |
| 83 | Ensures proper settings file is used in |
| 84 | setup_environ if DJANGO_SETTINGS_MODULE |
| 85 | is set in the environment. |
| 86 | """ |
| 87 | def setUp(self): |
| 88 | """ |
| 89 | Make sure DJANGO_SETTINGS_MODULE is not |
| 90 | permanently changed by these tests. |
| 91 | """ |
| 92 | def env_restore_func(): |
| 93 | original_value = os.environ.get('DJANGO_SETTINGS_MODULE') |
| 94 | |
| 95 | def blank_key(): |
| 96 | if 'DJANGO_SETTINGS_MODULE' in os.environ: |
| 97 | del(os.environ['DJANGO_SETTINGS_MODULE']) |
| 98 | |
| 99 | def restore_current(): |
| 100 | os.environ['DJANGO_SETTINGS_MODULE'] = original_value |
| 101 | |
| 102 | if original_value: |
| 103 | return restore_current |
| 104 | else: |
| 105 | return blank_key |
| 106 | |
| 107 | self.restore_env = env_restore_func() |
| 108 | |
| 109 | def test_env_var_used(self): |
| 110 | """ |
| 111 | If the environment variable is set, do |
| 112 | not ignore it. However, the kwarg |
| 113 | original_settings_path takes precedence. |
| 114 | |
| 115 | This tests both plus the default (neither set). |
| 116 | """ |
| 117 | from django.core.management import setup_environ |
| 118 | |
| 119 | #whatever was already there |
| 120 | original_module = os.environ.get( |
| 121 | 'DJANGO_SETTINGS_MODULE', |
| 122 | 'the default' |
| 123 | ) |
| 124 | |
| 125 | #environment variable set by user |
| 126 | user_override = 'custom.settings' |
| 127 | |
| 128 | #optional argument to setup_environ |
| 129 | orig_path = 'original.path' |
| 130 | |
| 131 | #expect default |
| 132 | setup_environ(global_settings) |
| 133 | self.assertEquals( |
| 134 | os.environ.get('DJANGO_SETTINGS_MODULE'), |
| 135 | original_module |
| 136 | ) |
| 137 | |
| 138 | #override with environment variable |
| 139 | os.environ['DJANGO_SETTINGS_MODULE'] = user_override |
| 140 | setup_environ(global_settings) |
| 141 | |
| 142 | self.assertEquals( |
| 143 | os.environ.get('DJANGO_SETTINGS_MODULE'), |
| 144 | user_override |
| 145 | ) |
| 146 | |
| 147 | #pass in original_settings_path (takes precedence) |
| 148 | os.environ['DJANGO_SETTINGS_MODULE'] = user_override |
| 149 | setup_environ(global_settings, original_settings_path = orig_path) |
| 150 | |
| 151 | self.assertEquals( |
| 152 | os.environ.get('DJANGO_SETTINGS_MODULE'), |
| 153 | orig_path |
| 154 | ) |
| 155 | |
| 156 | def tearDown(self): |
| 157 | self.restore_env() |
| 158 | |