| 104 | |
| 105 | |
| 106 | class EnvironmentVariableTest(TestCase): |
| 107 | """ |
| 108 | Ensures proper settings file is used in |
| 109 | setup_environ if DJANGO_SETTINGS_MODULE |
| 110 | is set in the environment. |
| 111 | """ |
| 112 | def setUp(self): |
| 113 | """ |
| 114 | Make sure DJANGO_SETTINGS_MODULE is not |
| 115 | permanently changed by these tests. |
| 116 | """ |
| 117 | def env_restore_func(): |
| 118 | original_value = os.environ.get('DJANGO_SETTINGS_MODULE') |
| 119 | |
| 120 | def blank_key(): |
| 121 | if 'DJANGO_SETTINGS_MODULE' in os.environ: |
| 122 | del(os.environ['DJANGO_SETTINGS_MODULE']) |
| 123 | |
| 124 | def restore_current(): |
| 125 | os.environ['DJANGO_SETTINGS_MODULE'] = original_value |
| 126 | |
| 127 | if original_value: |
| 128 | return restore_current |
| 129 | else: |
| 130 | return blank_key |
| 131 | |
| 132 | self.restore_env = env_restore_func() |
| 133 | |
| 134 | def test_env_var_used(self): |
| 135 | """ |
| 136 | If the environment variable is set, do |
| 137 | not ignore it. However, the kwarg |
| 138 | original_settings_path takes precedence. |
| 139 | |
| 140 | This tests both plus the default (neither set). |
| 141 | """ |
| 142 | from django.core.management import setup_environ |
| 143 | |
| 144 | #whatever was already there |
| 145 | original_module = os.environ.get( |
| 146 | 'DJANGO_SETTINGS_MODULE', |
| 147 | 'the default' |
| 148 | ) |
| 149 | |
| 150 | #environment variable set by user |
| 151 | user_override = 'custom.settings' |
| 152 | |
| 153 | #optional argument to setup_environ |
| 154 | orig_path = 'original.path' |
| 155 | |
| 156 | #expect default |
| 157 | setup_environ(global_settings) |
| 158 | self.assertEquals( |
| 159 | os.environ.get('DJANGO_SETTINGS_MODULE'), |
| 160 | original_module |
| 161 | ) |
| 162 | |
| 163 | #override with environment variable |
| 164 | os.environ['DJANGO_SETTINGS_MODULE'] = user_override |
| 165 | setup_environ(global_settings) |
| 166 | |
| 167 | self.assertEquals( |
| 168 | os.environ.get('DJANGO_SETTINGS_MODULE'), |
| 169 | user_override |
| 170 | ) |
| 171 | |
| 172 | #pass in original_settings_path (takes precedence) |
| 173 | os.environ['DJANGO_SETTINGS_MODULE'] = user_override |
| 174 | setup_environ(global_settings, original_settings_path = orig_path) |
| 175 | |
| 176 | self.assertEquals( |
| 177 | os.environ.get('DJANGO_SETTINGS_MODULE'), |
| 178 | orig_path |
| 179 | ) |
| 180 | |
| 181 | def tearDown(self): |
| 182 | self.restore_env() |
| 183 | |