22# Use of this source code is governed by a BSD-style
33# license that can be found in the LICENSE file.
44
5+
6+ import os
7+ import unittest .mock as mock
8+
59import google .api_core .exceptions
610import google .cloud .bigquery
711import pandas as pd
@@ -202,3 +206,52 @@ def test_create_user_agent(user_agent, rfc9110_delimiter, expected):
202206
203207 result = create_user_agent (user_agent , rfc9110_delimiter )
204208 assert result == expected
209+
210+
211+ @mock .patch .dict (os .environ , {"VSCODE_PID" : "1234" }, clear = True )
212+ def test_create_user_agent_vscode ():
213+ from pandas_gbq .gbq import create_user_agent
214+
215+ assert create_user_agent () == f"pandas-{ pd .__version__ } vscode"
216+
217+ @mock .patch .dict (os .environ , {"VSCODE_PID" : "1234" }, clear = True )
218+ def test_create_user_agent_vscode_plugin ():
219+ from pandas_gbq .gbq import create_user_agent
220+
221+ # simulate plugin installation by creating plugin config on disk
222+ user_home = os .path .expanduser ("~" )
223+ plugin_dir = os .path .join (user_home , ".vscode" , "extensions" , "googlecloudtools.cloudcode-0.12" )
224+ plugin_config = os .path .join (plugin_dir , "package.json" )
225+ assert not os .path .exists (plugin_config ) # initially does not exist
226+ os .makedirs (plugin_dir , exist_ok = True )
227+ with open (plugin_config , "w" ) as f :
228+ f .write ("{}" )
229+
230+ # test
231+ assert create_user_agent () == f"pandas-{ pd .__version__ } vscode googlecloudtools.cloudcode"
232+
233+ # clean up disk
234+ os .remove (plugin_config )
235+
236+
237+ @mock .patch .dict (os .environ , {"JPY_PARENT_PID" : "1234" }, clear = True )
238+ def test_create_user_agent_jupyter ():
239+ from pandas_gbq .gbq import create_user_agent
240+
241+ assert create_user_agent () == f"pandas-{ pd .__version__ } jupyter"
242+
243+
244+ @mock .patch .dict (os .environ , {"JPY_PARENT_PID" : "1234" }, clear = True )
245+ def test_create_user_agent_jupyter_extension ():
246+ from pandas_gbq .gbq import create_user_agent
247+
248+ def custom_import_module_side_effect (name , package = None ):
249+ print (f" [Test Mock] Intercepted importlib.import_module for '{ name } '" )
250+ if name == "bigquery_jupyter_plugin" :
251+ return mock .MagicMock ()
252+ else :
253+ import importlib
254+ return importlib .import_module (name , package )
255+
256+ with mock .patch ('importlib.import_module' , side_effect = custom_import_module_side_effect ):
257+ assert create_user_agent () == f"pandas-{ pd .__version__ } jupyter bigquery_jupyter_plugin"
0 commit comments