|
1 | 1 | #!/usr/bin/env python3 |
2 | 2 | """Test for the ee.__init__ file.""" |
3 | 3 |
|
| 4 | +import os |
4 | 5 | from unittest import mock |
5 | 6 |
|
6 | 7 | import google.auth |
@@ -53,6 +54,67 @@ def MockAlgorithms(): |
53 | 54 | self.assertEqual(ee.ApiFunction._api, {}) |
54 | 55 | self.assertFalse(ee.Image._initialized) |
55 | 56 |
|
| 57 | + def testProjectInitialization(self): |
| 58 | + """Verifies that we can fetch the client project from many locations. |
| 59 | +
|
| 60 | + This also exercises the logic in data.get_persistent_credentials. |
| 61 | + """ |
| 62 | + |
| 63 | + cred_args = dict(refresh_token='rt', quota_project_id='qp1') |
| 64 | + google_creds = credentials.Credentials(token=None, quota_project_id='qp2') |
| 65 | + expected_project = None |
| 66 | + |
| 67 | + def CheckDataInit(**kwargs): |
| 68 | + self.assertEqual(expected_project, kwargs.get('project')) |
| 69 | + |
| 70 | + moc = mock.patch.object |
| 71 | + with (moc(ee.oauth, 'get_credentials_arguments', new=lambda: cred_args), |
| 72 | + moc(ee.oauth, 'is_valid_credentials', new=lambda _: True), |
| 73 | + moc(google.auth, 'default', new=lambda: (google_creds, None)), |
| 74 | + moc(ee.data, 'initialize', side_effect=CheckDataInit) as inits): |
| 75 | + expected_project = 'qp0' |
| 76 | + ee.Initialize(project='qp0') |
| 77 | + |
| 78 | + expected_project = 'qp1' |
| 79 | + ee.Initialize() |
| 80 | + |
| 81 | + cred_args['refresh_token'] = None |
| 82 | + ee.Initialize() |
| 83 | + |
| 84 | + cred_args['quota_project_id'] = None |
| 85 | + expected_project = 'qp2' |
| 86 | + ee.Initialize() |
| 87 | + |
| 88 | + google_creds = google_creds.with_quota_project(None) |
| 89 | + expected_project = None |
| 90 | + ee.Initialize() |
| 91 | + |
| 92 | + expected_project = 'qp3' |
| 93 | + with mock.patch.dict( |
| 94 | + os.environ, |
| 95 | + {'EE_PROJECT_ID': expected_project, 'GOOGLE_CLOUD_PROJECT': 'qp4'}, |
| 96 | + ): |
| 97 | + ee.Initialize() |
| 98 | + |
| 99 | + expected_project = 'qp4' |
| 100 | + with mock.patch.dict( |
| 101 | + os.environ, {'GOOGLE_CLOUD_PROJECT': expected_project} |
| 102 | + ): |
| 103 | + ee.Initialize() |
| 104 | + self.assertEqual(7, inits.call_count) |
| 105 | + |
| 106 | + expected_project = None |
| 107 | + msg = 'Earth Engine API has not been used in project 764086051850 before' |
| 108 | + with moc(ee.ApiFunction, 'initialize', side_effect=ee.EEException(msg)): |
| 109 | + with self.assertRaisesRegex(ee.EEException, '.*no project found..*'): |
| 110 | + ee.Initialize() |
| 111 | + |
| 112 | + cred_args['client_id'] = '764086051850-xxx' # dummy usable-auth client |
| 113 | + cred_args['refresh_token'] = 'rt' |
| 114 | + with self.assertRaisesRegex(ee.EEException, '.*no project found..*'): |
| 115 | + ee.Initialize() |
| 116 | + self.assertEqual(8, inits.call_count) |
| 117 | + |
56 | 118 | def testCallAndApply(self): |
57 | 119 | """Verifies library initialization.""" |
58 | 120 |
|
|
0 commit comments