test_core.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188
  1. # -*- coding: utf-8 -*-
  2. """
  3. :codeauthor: Erik Johnson <erik@saltstack.com>
  4. """
  5. # Import Python libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import logging
  8. import os
  9. import platform
  10. import socket
  11. import textwrap
  12. import salt.grains.core as core
  13. import salt.modules.cmdmod
  14. import salt.modules.network
  15. import salt.modules.smbios
  16. # Import Salt Libs
  17. import salt.utils.dns
  18. import salt.utils.files
  19. import salt.utils.network
  20. import salt.utils.path
  21. import salt.utils.platform
  22. from salt._compat import ipaddress
  23. # Import 3rd-party libs
  24. from salt.ext import six
  25. from tests.support.mixins import LoaderModuleMockMixin
  26. from tests.support.mock import MagicMock, Mock, mock_open, patch
  27. from tests.support.unit import TestCase, skipIf
  28. # Import Salt Testing Libs
  29. try:
  30. import pytest
  31. except ImportError as import_error:
  32. pytest = None
  33. log = logging.getLogger(__name__)
  34. # Globals
  35. IPv4Address = ipaddress.IPv4Address
  36. IPv6Address = ipaddress.IPv6Address
  37. IP4_LOCAL = "127.0.0.1"
  38. IP4_ADD1 = "10.0.0.1"
  39. IP4_ADD2 = "10.0.0.2"
  40. IP6_LOCAL = "::1"
  41. IP6_ADD1 = "2001:4860:4860::8844"
  42. IP6_ADD2 = "2001:4860:4860::8888"
  43. IP6_ADD_SCOPE = "fe80::6238:e0ff:fe06:3f6b%enp2s0"
  44. OS_RELEASE_DIR = os.path.join(os.path.dirname(__file__), "os-releases")
  45. SOLARIS_DIR = os.path.join(os.path.dirname(__file__), "solaris")
  46. @skipIf(not pytest, False)
  47. class CoreGrainsTestCase(TestCase, LoaderModuleMockMixin):
  48. """
  49. Test cases for core grains
  50. """
  51. def setup_loader_modules(self):
  52. return {core: {}}
  53. @patch("os.path.isfile")
  54. def test_parse_etc_os_release(self, path_isfile_mock):
  55. path_isfile_mock.side_effect = lambda x: x == "/usr/lib/os-release"
  56. with salt.utils.files.fopen(
  57. os.path.join(OS_RELEASE_DIR, "ubuntu-17.10")
  58. ) as os_release_file:
  59. os_release_content = os_release_file.read()
  60. with patch("salt.utils.files.fopen", mock_open(read_data=os_release_content)):
  61. os_release = core._parse_os_release(
  62. "/etc/os-release", "/usr/lib/os-release"
  63. )
  64. self.assertEqual(
  65. os_release,
  66. {
  67. "NAME": "Ubuntu",
  68. "VERSION": "17.10 (Artful Aardvark)",
  69. "ID": "ubuntu",
  70. "ID_LIKE": "debian",
  71. "PRETTY_NAME": "Ubuntu 17.10",
  72. "VERSION_ID": "17.10",
  73. "HOME_URL": "https://www.ubuntu.com/",
  74. "SUPPORT_URL": "https://help.ubuntu.com/",
  75. "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/",
  76. "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy",
  77. "VERSION_CODENAME": "artful",
  78. "UBUNTU_CODENAME": "artful",
  79. },
  80. )
  81. def test_parse_cpe_name_wfn(self):
  82. """
  83. Parse correct CPE_NAME data WFN formatted
  84. :return:
  85. """
  86. for cpe, cpe_ret in [
  87. (
  88. "cpe:/o:opensuse:leap:15.0",
  89. {
  90. "phase": None,
  91. "version": "15.0",
  92. "product": "leap",
  93. "vendor": "opensuse",
  94. "part": "operating system",
  95. },
  96. ),
  97. (
  98. "cpe:/o:vendor:product:42:beta",
  99. {
  100. "phase": "beta",
  101. "version": "42",
  102. "product": "product",
  103. "vendor": "vendor",
  104. "part": "operating system",
  105. },
  106. ),
  107. ]:
  108. ret = core._parse_cpe_name(cpe)
  109. for key in cpe_ret:
  110. assert key in ret
  111. assert cpe_ret[key] == ret[key]
  112. def test_parse_cpe_name_v23(self):
  113. """
  114. Parse correct CPE_NAME data v2.3 formatted
  115. :return:
  116. """
  117. for cpe, cpe_ret in [
  118. (
  119. "cpe:2.3:o:microsoft:windows_xp:5.1.601:beta:*:*:*:*:*:*",
  120. {
  121. "phase": "beta",
  122. "version": "5.1.601",
  123. "product": "windows_xp",
  124. "vendor": "microsoft",
  125. "part": "operating system",
  126. },
  127. ),
  128. (
  129. "cpe:2.3:h:corellian:millenium_falcon:1.0:*:*:*:*:*:*:*",
  130. {
  131. "phase": None,
  132. "version": "1.0",
  133. "product": "millenium_falcon",
  134. "vendor": "corellian",
  135. "part": "hardware",
  136. },
  137. ),
  138. (
  139. "cpe:2.3:*:dark_empire:light_saber:3.0:beta:*:*:*:*:*:*",
  140. {
  141. "phase": "beta",
  142. "version": "3.0",
  143. "product": "light_saber",
  144. "vendor": "dark_empire",
  145. "part": None,
  146. },
  147. ),
  148. ]:
  149. ret = core._parse_cpe_name(cpe)
  150. for key in cpe_ret:
  151. assert key in ret
  152. assert cpe_ret[key] == ret[key]
  153. def test_parse_cpe_name_broken(self):
  154. """
  155. Parse broken CPE_NAME data
  156. :return:
  157. """
  158. for cpe in [
  159. "cpe:broken",
  160. "cpe:broken:in:all:ways:*:*:*:*",
  161. "cpe:x:still:broken:123",
  162. "who:/knows:what:is:here",
  163. ]:
  164. assert core._parse_cpe_name(cpe) == {}
  165. def test_missing_os_release(self):
  166. with patch("salt.utils.files.fopen", mock_open(read_data={})):
  167. os_release = core._parse_os_release(
  168. "/etc/os-release", "/usr/lib/os-release"
  169. )
  170. self.assertEqual(os_release, {})
  171. @skipIf(not salt.utils.platform.is_windows(), "System is not Windows")
  172. def test__windows_platform_data(self):
  173. grains = core._windows_platform_data()
  174. keys = [
  175. "biosversion",
  176. "osrelease",
  177. "kernelrelease",
  178. "motherboard",
  179. "serialnumber",
  180. "timezone",
  181. "manufacturer",
  182. "kernelversion",
  183. "osservicepack",
  184. "virtual",
  185. "productname",
  186. "osfullname",
  187. "osmanufacturer",
  188. "osversion",
  189. "windowsdomain",
  190. ]
  191. for key in keys:
  192. self.assertIn(key, grains)
  193. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  194. def test_gnu_slash_linux_in_os_name(self):
  195. """
  196. Test to return a list of all enabled services
  197. """
  198. _path_exists_map = {"/proc/1/cmdline": False}
  199. _path_isfile_map = {}
  200. _cmd_run_map = {
  201. "dpkg --print-architecture": "amd64",
  202. }
  203. path_exists_mock = MagicMock(side_effect=lambda x: _path_exists_map[x])
  204. path_isfile_mock = MagicMock(
  205. side_effect=lambda x: _path_isfile_map.get(x, False)
  206. )
  207. cmd_run_mock = MagicMock(side_effect=lambda x: _cmd_run_map[x])
  208. empty_mock = MagicMock(return_value={})
  209. orig_import = __import__
  210. if six.PY2:
  211. built_in = "__builtin__"
  212. else:
  213. built_in = "builtins"
  214. def _import_mock(name, *args):
  215. if name == "lsb_release":
  216. raise ImportError("No module named lsb_release")
  217. return orig_import(name, *args)
  218. # - Skip the first if statement
  219. # - Skip the selinux/systemd stuff (not pertinent)
  220. # - Skip the init grain compilation (not pertinent)
  221. # - Ensure that lsb_release fails to import
  222. # - Skip all the /etc/*-release stuff (not pertinent)
  223. # - Mock _linux_distribution to give us the OS name that we want
  224. # - Make a bunch of functions return empty dicts, we don't care about
  225. # these grains for the purposes of this test.
  226. # - Mock the osarch
  227. distro_mock = MagicMock(return_value=("Debian GNU/Linux", "8.3", ""))
  228. with patch.object(
  229. salt.utils.platform, "is_proxy", MagicMock(return_value=False)
  230. ), patch.object(
  231. core, "_linux_bin_exists", MagicMock(return_value=False)
  232. ), patch.object(
  233. os.path, "exists", path_exists_mock
  234. ), patch(
  235. "{0}.__import__".format(built_in), side_effect=_import_mock
  236. ), patch.object(
  237. os.path, "isfile", path_isfile_mock
  238. ), patch.object(
  239. core, "_parse_lsb_release", empty_mock
  240. ), patch.object(
  241. core, "_parse_os_release", empty_mock
  242. ), patch.object(
  243. core, "_parse_lsb_release", empty_mock
  244. ), patch.object(
  245. core, "_linux_distribution", distro_mock
  246. ), patch.object(
  247. core, "_linux_cpudata", empty_mock
  248. ), patch.object(
  249. core, "_linux_gpu_data", empty_mock
  250. ), patch.object(
  251. core, "_memdata", empty_mock
  252. ), patch.object(
  253. core, "_hw_data", empty_mock
  254. ), patch.object(
  255. core, "_virtual", empty_mock
  256. ), patch.object(
  257. core, "_ps", empty_mock
  258. ), patch.dict(
  259. core.__salt__, {"cmd.run": cmd_run_mock}
  260. ):
  261. os_grains = core.os_data()
  262. self.assertEqual(os_grains.get("os_family"), "Debian")
  263. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  264. def test_suse_os_from_cpe_data(self):
  265. """
  266. Test if 'os' grain is parsed from CPE_NAME of /etc/os-release
  267. """
  268. _path_exists_map = {"/proc/1/cmdline": False}
  269. _os_release_map = {
  270. "NAME": "SLES",
  271. "VERSION": "12-SP1",
  272. "VERSION_ID": "12.1",
  273. "PRETTY_NAME": "SUSE Linux Enterprise Server 12 SP1",
  274. "ID": "sles",
  275. "ANSI_COLOR": "0;32",
  276. "CPE_NAME": "cpe:/o:suse:sles:12:sp1",
  277. }
  278. path_exists_mock = MagicMock(side_effect=lambda x: _path_exists_map[x])
  279. empty_mock = MagicMock(return_value={})
  280. osarch_mock = MagicMock(return_value="amd64")
  281. os_release_mock = MagicMock(return_value=_os_release_map)
  282. orig_import = __import__
  283. if six.PY2:
  284. built_in = "__builtin__"
  285. else:
  286. built_in = "builtins"
  287. def _import_mock(name, *args):
  288. if name == "lsb_release":
  289. raise ImportError("No module named lsb_release")
  290. return orig_import(name, *args)
  291. distro_mock = MagicMock(
  292. return_value=("SUSE Linux Enterprise Server ", "12", "x86_64")
  293. )
  294. # - Skip the first if statement
  295. # - Skip the selinux/systemd stuff (not pertinent)
  296. # - Skip the init grain compilation (not pertinent)
  297. # - Ensure that lsb_release fails to import
  298. # - Skip all the /etc/*-release stuff (not pertinent)
  299. # - Mock _linux_distribution to give us the OS name that we want
  300. # - Mock the osarch
  301. with patch.object(
  302. salt.utils.platform, "is_proxy", MagicMock(return_value=False)
  303. ), patch.object(
  304. core, "_linux_bin_exists", MagicMock(return_value=False)
  305. ), patch.object(
  306. os.path, "exists", path_exists_mock
  307. ), patch(
  308. "{0}.__import__".format(built_in), side_effect=_import_mock
  309. ), patch.object(
  310. os.path, "isfile", MagicMock(return_value=False)
  311. ), patch.object(
  312. core, "_parse_os_release", os_release_mock
  313. ), patch.object(
  314. core, "_parse_lsb_release", empty_mock
  315. ), patch.object(
  316. core, "_linux_distribution", distro_mock
  317. ), patch.object(
  318. core, "_linux_gpu_data", empty_mock
  319. ), patch.object(
  320. core, "_hw_data", empty_mock
  321. ), patch.object(
  322. core, "_linux_cpudata", empty_mock
  323. ), patch.object(
  324. core, "_virtual", empty_mock
  325. ), patch.dict(
  326. core.__salt__, {"cmd.run": osarch_mock}
  327. ):
  328. os_grains = core.os_data()
  329. self.assertEqual(os_grains.get("os_family"), "Suse")
  330. self.assertEqual(os_grains.get("os"), "SUSE")
  331. def _run_os_grains_tests(self, os_release_filename, os_release_map, expectation):
  332. path_isfile_mock = MagicMock(
  333. side_effect=lambda x: x in os_release_map.get("files", [])
  334. )
  335. empty_mock = MagicMock(return_value={})
  336. osarch_mock = MagicMock(return_value="amd64")
  337. if os_release_filename:
  338. os_release_data = core._parse_os_release(
  339. os.path.join(OS_RELEASE_DIR, os_release_filename)
  340. )
  341. else:
  342. os_release_data = os_release_map.get("os_release_file", {})
  343. os_release_mock = MagicMock(return_value=os_release_data)
  344. orig_import = __import__
  345. if six.PY2:
  346. built_in = "__builtin__"
  347. else:
  348. built_in = "builtins"
  349. def _import_mock(name, *args):
  350. if name == "lsb_release":
  351. raise ImportError("No module named lsb_release")
  352. return orig_import(name, *args)
  353. suse_release_file = os_release_map.get("suse_release_file")
  354. file_contents = {"/proc/1/cmdline": ""}
  355. if suse_release_file:
  356. file_contents["/etc/SuSE-release"] = suse_release_file
  357. # - Skip the first if statement
  358. # - Skip the selinux/systemd stuff (not pertinent)
  359. # - Skip the init grain compilation (not pertinent)
  360. # - Ensure that lsb_release fails to import
  361. # - Skip all the /etc/*-release stuff (not pertinent)
  362. # - Mock _linux_distribution to give us the OS name that we want
  363. # - Mock the osarch
  364. distro_mock = MagicMock(return_value=os_release_map["_linux_distribution"])
  365. with patch.object(
  366. salt.utils.platform, "is_proxy", MagicMock(return_value=False)
  367. ), patch.object(
  368. core, "_linux_bin_exists", MagicMock(return_value=False)
  369. ), patch.object(
  370. os.path, "exists", path_isfile_mock
  371. ), patch(
  372. "{0}.__import__".format(built_in), side_effect=_import_mock
  373. ), patch.object(
  374. os.path, "isfile", path_isfile_mock
  375. ), patch.object(
  376. core, "_parse_os_release", os_release_mock
  377. ), patch.object(
  378. core, "_parse_lsb_release", empty_mock
  379. ), patch(
  380. "salt.utils.files.fopen", mock_open(read_data=file_contents)
  381. ), patch.object(
  382. core, "_linux_distribution", distro_mock
  383. ), patch.object(
  384. core, "_linux_gpu_data", empty_mock
  385. ), patch.object(
  386. core, "_linux_cpudata", empty_mock
  387. ), patch.object(
  388. core, "_virtual", empty_mock
  389. ), patch.dict(
  390. core.__salt__, {"cmd.run": osarch_mock}
  391. ):
  392. os_grains = core.os_data()
  393. grains = {
  394. k: v
  395. for k, v in os_grains.items()
  396. if k
  397. in set(
  398. [
  399. "os",
  400. "os_family",
  401. "osfullname",
  402. "oscodename",
  403. "osfinger",
  404. "osrelease",
  405. "osrelease_info",
  406. "osmajorrelease",
  407. ]
  408. )
  409. }
  410. self.assertEqual(grains, expectation)
  411. def _run_suse_os_grains_tests(self, os_release_map, expectation):
  412. os_release_map["_linux_distribution"] = ("SUSE test", "version", "arch")
  413. expectation["os"] = "SUSE"
  414. expectation["os_family"] = "Suse"
  415. self._run_os_grains_tests(None, os_release_map, expectation)
  416. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  417. def test_suse_os_grains_sles11sp3(self):
  418. """
  419. Test if OS grains are parsed correctly in SLES 11 SP3
  420. """
  421. _os_release_map = {
  422. "suse_release_file": textwrap.dedent(
  423. """
  424. SUSE Linux Enterprise Server 11 (x86_64)
  425. VERSION = 11
  426. PATCHLEVEL = 3
  427. """
  428. ),
  429. "files": ["/etc/SuSE-release"],
  430. }
  431. expectation = {
  432. "oscodename": "SUSE Linux Enterprise Server 11 SP3",
  433. "osfullname": "SLES",
  434. "osrelease": "11.3",
  435. "osrelease_info": (11, 3),
  436. "osmajorrelease": 11,
  437. "osfinger": "SLES-11",
  438. }
  439. self._run_suse_os_grains_tests(_os_release_map, expectation)
  440. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  441. def test_suse_os_grains_sles11sp4(self):
  442. """
  443. Test if OS grains are parsed correctly in SLES 11 SP4
  444. """
  445. _os_release_map = {
  446. "os_release_file": {
  447. "NAME": "SLES",
  448. "VERSION": "11.4",
  449. "VERSION_ID": "11.4",
  450. "PRETTY_NAME": "SUSE Linux Enterprise Server 11 SP4",
  451. "ID": "sles",
  452. "ANSI_COLOR": "0;32",
  453. "CPE_NAME": "cpe:/o:suse:sles:11:4",
  454. },
  455. }
  456. expectation = {
  457. "oscodename": "SUSE Linux Enterprise Server 11 SP4",
  458. "osfullname": "SLES",
  459. "osrelease": "11.4",
  460. "osrelease_info": (11, 4),
  461. "osmajorrelease": 11,
  462. "osfinger": "SLES-11",
  463. }
  464. self._run_suse_os_grains_tests(_os_release_map, expectation)
  465. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  466. def test_suse_os_grains_sles12(self):
  467. """
  468. Test if OS grains are parsed correctly in SLES 12
  469. """
  470. _os_release_map = {
  471. "os_release_file": {
  472. "NAME": "SLES",
  473. "VERSION": "12",
  474. "VERSION_ID": "12",
  475. "PRETTY_NAME": "SUSE Linux Enterprise Server 12",
  476. "ID": "sles",
  477. "ANSI_COLOR": "0;32",
  478. "CPE_NAME": "cpe:/o:suse:sles:12",
  479. },
  480. }
  481. expectation = {
  482. "oscodename": "SUSE Linux Enterprise Server 12",
  483. "osfullname": "SLES",
  484. "osrelease": "12",
  485. "osrelease_info": (12,),
  486. "osmajorrelease": 12,
  487. "osfinger": "SLES-12",
  488. }
  489. self._run_suse_os_grains_tests(_os_release_map, expectation)
  490. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  491. def test_suse_os_grains_sles12sp1(self):
  492. """
  493. Test if OS grains are parsed correctly in SLES 12 SP1
  494. """
  495. _os_release_map = {
  496. "os_release_file": {
  497. "NAME": "SLES",
  498. "VERSION": "12-SP1",
  499. "VERSION_ID": "12.1",
  500. "PRETTY_NAME": "SUSE Linux Enterprise Server 12 SP1",
  501. "ID": "sles",
  502. "ANSI_COLOR": "0;32",
  503. "CPE_NAME": "cpe:/o:suse:sles:12:sp1",
  504. },
  505. }
  506. expectation = {
  507. "oscodename": "SUSE Linux Enterprise Server 12 SP1",
  508. "osfullname": "SLES",
  509. "osrelease": "12.1",
  510. "osrelease_info": (12, 1),
  511. "osmajorrelease": 12,
  512. "osfinger": "SLES-12",
  513. }
  514. self._run_suse_os_grains_tests(_os_release_map, expectation)
  515. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  516. def test_suse_os_grains_opensuse_leap_42_1(self):
  517. """
  518. Test if OS grains are parsed correctly in openSUSE Leap 42.1
  519. """
  520. _os_release_map = {
  521. "os_release_file": {
  522. "NAME": "openSUSE Leap",
  523. "VERSION": "42.1",
  524. "VERSION_ID": "42.1",
  525. "PRETTY_NAME": "openSUSE Leap 42.1 (x86_64)",
  526. "ID": "opensuse",
  527. "ANSI_COLOR": "0;32",
  528. "CPE_NAME": "cpe:/o:opensuse:opensuse:42.1",
  529. },
  530. }
  531. expectation = {
  532. "oscodename": "openSUSE Leap 42.1 (x86_64)",
  533. "osfullname": "Leap",
  534. "osrelease": "42.1",
  535. "osrelease_info": (42, 1),
  536. "osmajorrelease": 42,
  537. "osfinger": "Leap-42",
  538. }
  539. self._run_suse_os_grains_tests(_os_release_map, expectation)
  540. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  541. def test_suse_os_grains_tumbleweed(self):
  542. """
  543. Test if OS grains are parsed correctly in openSUSE Tumbleweed
  544. """
  545. _os_release_map = {
  546. "os_release_file": {
  547. "NAME": "openSUSE",
  548. "VERSION": "Tumbleweed",
  549. "VERSION_ID": "20160504",
  550. "PRETTY_NAME": "openSUSE Tumbleweed (20160504) (x86_64)",
  551. "ID": "opensuse",
  552. "ANSI_COLOR": "0;32",
  553. "CPE_NAME": "cpe:/o:opensuse:opensuse:20160504",
  554. },
  555. }
  556. expectation = {
  557. "oscodename": "openSUSE Tumbleweed (20160504) (x86_64)",
  558. "osfullname": "Tumbleweed",
  559. "osrelease": "20160504",
  560. "osrelease_info": (20160504,),
  561. "osmajorrelease": 20160504,
  562. "osfinger": "Tumbleweed-20160504",
  563. }
  564. self._run_suse_os_grains_tests(_os_release_map, expectation)
  565. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  566. def test_debian_7_os_grains(self):
  567. """
  568. Test if OS grains are parsed correctly in Debian 7 "wheezy"
  569. """
  570. _os_release_map = {
  571. "_linux_distribution": ("debian", "7.11", ""),
  572. }
  573. expectation = {
  574. "os": "Debian",
  575. "os_family": "Debian",
  576. "oscodename": "wheezy",
  577. "osfullname": "Debian GNU/Linux",
  578. "osrelease": "7",
  579. "osrelease_info": (7,),
  580. "osmajorrelease": 7,
  581. "osfinger": "Debian-7",
  582. }
  583. self._run_os_grains_tests("debian-7", _os_release_map, expectation)
  584. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  585. def test_debian_8_os_grains(self):
  586. """
  587. Test if OS grains are parsed correctly in Debian 8 "jessie"
  588. """
  589. _os_release_map = {
  590. "_linux_distribution": ("debian", "8.10", ""),
  591. }
  592. expectation = {
  593. "os": "Debian",
  594. "os_family": "Debian",
  595. "oscodename": "jessie",
  596. "osfullname": "Debian GNU/Linux",
  597. "osrelease": "8",
  598. "osrelease_info": (8,),
  599. "osmajorrelease": 8,
  600. "osfinger": "Debian-8",
  601. }
  602. self._run_os_grains_tests("debian-8", _os_release_map, expectation)
  603. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  604. def test_debian_9_os_grains(self):
  605. """
  606. Test if OS grains are parsed correctly in Debian 9 "stretch"
  607. """
  608. _os_release_map = {
  609. "_linux_distribution": ("debian", "9.3", ""),
  610. }
  611. expectation = {
  612. "os": "Debian",
  613. "os_family": "Debian",
  614. "oscodename": "stretch",
  615. "osfullname": "Debian GNU/Linux",
  616. "osrelease": "9",
  617. "osrelease_info": (9,),
  618. "osmajorrelease": 9,
  619. "osfinger": "Debian-9",
  620. }
  621. self._run_os_grains_tests("debian-9", _os_release_map, expectation)
  622. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  623. def test_centos_8_os_grains(self):
  624. """
  625. Test if OS grains are parsed correctly in Centos 8
  626. """
  627. _os_release_map = {
  628. "os_release_file": {
  629. "NAME": "CentOS Linux",
  630. "VERSION": "8 (Core)",
  631. "VERSION_ID": "8",
  632. "PRETTY_NAME": "CentOS Linux 8 (Core)",
  633. "ID": "centos",
  634. "ANSI_COLOR": "0;31",
  635. "CPE_NAME": "cpe:/o:centos:centos:8",
  636. },
  637. "_linux_distribution": ("centos", "8.1.1911", "Core"),
  638. }
  639. expectation = {
  640. "os": "CentOS",
  641. "os_family": "RedHat",
  642. "oscodename": "CentOS Linux 8 (Core)",
  643. "osfullname": "CentOS Linux",
  644. "osrelease": "8.1.1911",
  645. "osrelease_info": (8, 1, 1911),
  646. "osmajorrelease": 8,
  647. "osfinger": "CentOS Linux-8",
  648. }
  649. self._run_os_grains_tests(None, _os_release_map, expectation)
  650. def test_unicode_error(self):
  651. raise_unicode_mock = MagicMock(
  652. name="raise_unicode_error", side_effect=UnicodeError
  653. )
  654. with patch("salt.grains.core.hostname"):
  655. with patch("socket.getaddrinfo", raise_unicode_mock):
  656. ret = salt.grains.core.ip_fqdn()
  657. assert ret["fqdn_ip4"] == ret["fqdn_ip6"] == []
  658. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  659. def test_ubuntu_xenial_os_grains(self):
  660. """
  661. Test if OS grains are parsed correctly in Ubuntu 16.04 "Xenial Xerus"
  662. """
  663. _os_release_map = {
  664. "_linux_distribution": ("Ubuntu", "16.04", "xenial"),
  665. }
  666. expectation = {
  667. "os": "Ubuntu",
  668. "os_family": "Debian",
  669. "oscodename": "xenial",
  670. "osfullname": "Ubuntu",
  671. "osrelease": "16.04",
  672. "osrelease_info": (16, 4),
  673. "osmajorrelease": 16,
  674. "osfinger": "Ubuntu-16.04",
  675. }
  676. self._run_os_grains_tests("ubuntu-16.04", _os_release_map, expectation)
  677. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  678. def test_ubuntu_artful_os_grains(self):
  679. """
  680. Test if OS grains are parsed correctly in Ubuntu 17.10 "Artful Aardvark"
  681. """
  682. _os_release_map = {
  683. "_linux_distribution": ("Ubuntu", "17.10", "artful"),
  684. }
  685. expectation = {
  686. "os": "Ubuntu",
  687. "os_family": "Debian",
  688. "oscodename": "artful",
  689. "osfullname": "Ubuntu",
  690. "osrelease": "17.10",
  691. "osrelease_info": (17, 10),
  692. "osmajorrelease": 17,
  693. "osfinger": "Ubuntu-17.10",
  694. }
  695. self._run_os_grains_tests("ubuntu-17.10", _os_release_map, expectation)
  696. @skipIf(not salt.utils.platform.is_windows(), "System is not Windows")
  697. def test_windows_platform_data(self):
  698. """
  699. Test the _windows_platform_data function
  700. """
  701. grains = [
  702. "biosversion",
  703. "kernelrelease",
  704. "kernelversion",
  705. "manufacturer",
  706. "motherboard",
  707. "osfullname",
  708. "osmanufacturer",
  709. "osrelease",
  710. "osservicepack",
  711. "osversion",
  712. "productname",
  713. "serialnumber",
  714. "timezone",
  715. "virtual",
  716. "windowsdomain",
  717. "windowsdomaintype",
  718. ]
  719. returned_grains = core._windows_platform_data()
  720. for grain in grains:
  721. self.assertIn(grain, returned_grains)
  722. valid_types = ["Unknown", "Unjoined", "Workgroup", "Domain"]
  723. self.assertIn(returned_grains["windowsdomaintype"], valid_types)
  724. valid_releases = [
  725. "Vista",
  726. "7",
  727. "8",
  728. "8.1",
  729. "10",
  730. "2008Server",
  731. "2008ServerR2",
  732. "2012Server",
  733. "2012ServerR2",
  734. "2016Server",
  735. "2019Server",
  736. ]
  737. self.assertIn(returned_grains["osrelease"], valid_releases)
  738. def test__windows_os_release_grain(self):
  739. versions = {
  740. "Windows 10 Home": "10",
  741. "Windows 10 Pro": "10",
  742. "Windows 10 Pro for Workstations": "10",
  743. "Windows 10 Pro Education": "10",
  744. "Windows 10 Enterprise": "10",
  745. "Windows 10 Enterprise LTSB": "10",
  746. "Windows 10 Education": "10",
  747. "Windows 10 IoT Core": "10",
  748. "Windows 10 IoT Enterprise": "10",
  749. "Windows 10 S": "10",
  750. "Windows 8.1": "8.1",
  751. "Windows 8.1 Pro": "8.1",
  752. "Windows 8.1 Enterprise": "8.1",
  753. "Windows 8.1 OEM": "8.1",
  754. "Windows 8.1 with Bing": "8.1",
  755. "Windows 8": "8",
  756. "Windows 8 Pro": "8",
  757. "Windows 8 Enterprise": "8",
  758. "Windows 8 OEM": "8",
  759. "Windows 7 Starter": "7",
  760. "Windows 7 Home Basic": "7",
  761. "Windows 7 Home Premium": "7",
  762. "Windows 7 Professional": "7",
  763. "Windows 7 Enterprise": "7",
  764. "Windows 7 Ultimate": "7",
  765. "Windows Thin PC": "Thin",
  766. "Windows Vista Starter": "Vista",
  767. "Windows Vista Home Basic": "Vista",
  768. "Windows Vista Home Premium": "Vista",
  769. "Windows Vista Business": "Vista",
  770. "Windows Vista Enterprise": "Vista",
  771. "Windows Vista Ultimate": "Vista",
  772. "Windows Server 2019 Essentials": "2019Server",
  773. "Windows Server 2019 Standard": "2019Server",
  774. "Windows Server 2019 Datacenter": "2019Server",
  775. "Windows Server 2016 Essentials": "2016Server",
  776. "Windows Server 2016 Standard": "2016Server",
  777. "Windows Server 2016 Datacenter": "2016Server",
  778. "Windows Server 2012 R2 Foundation": "2012ServerR2",
  779. "Windows Server 2012 R2 Essentials": "2012ServerR2",
  780. "Windows Server 2012 R2 Standard": "2012ServerR2",
  781. "Windows Server 2012 R2 Datacenter": "2012ServerR2",
  782. "Windows Server 2012 Foundation": "2012Server",
  783. "Windows Server 2012 Essentials": "2012Server",
  784. "Windows Server 2012 Standard": "2012Server",
  785. "Windows Server 2012 Datacenter": "2012Server",
  786. "Windows MultiPoint Server 2012": "2012Server",
  787. "Windows Small Business Server 2011": "2011Server",
  788. "Windows MultiPoint Server 2011": "2011Server",
  789. "Windows Home Server 2011": "2011Server",
  790. "Windows MultiPoint Server 2010": "2010Server",
  791. "Windows Server 2008 R2 Foundation": "2008ServerR2",
  792. "Windows Server 2008 R2 Standard": "2008ServerR2",
  793. "Windows Server 2008 R2 Enterprise": "2008ServerR2",
  794. "Windows Server 2008 R2 Datacenter": "2008ServerR2",
  795. "Windows Server 2008 R2 for Itanium-based Systems": "2008ServerR2",
  796. "Windows Web Server 2008 R2": "2008ServerR2",
  797. "Windows Storage Server 2008 R2": "2008ServerR2",
  798. "Windows HPC Server 2008 R2": "2008ServerR2",
  799. "Windows Server 2008 Standard": "2008Server",
  800. "Windows Server 2008 Enterprise": "2008Server",
  801. "Windows Server 2008 Datacenter": "2008Server",
  802. "Windows Server 2008 for Itanium-based Systems": "2008Server",
  803. "Windows Server Foundation 2008": "2008Server",
  804. "Windows Essential Business Server 2008": "2008Server",
  805. "Windows HPC Server 2008": "2008Server",
  806. "Windows Small Business Server 2008": "2008Server",
  807. "Windows Storage Server 2008": "2008Server",
  808. "Windows Web Server 2008": "2008Server",
  809. }
  810. for caption in versions:
  811. version = core._windows_os_release_grain(caption, 1)
  812. self.assertEqual(
  813. version,
  814. versions[caption],
  815. "version: {0}\n"
  816. "found: {1}\n"
  817. "caption: {2}".format(version, versions[caption], caption),
  818. )
  819. embedded_versions = {
  820. "Windows Embedded 8.1 Industry Pro": "8.1",
  821. "Windows Embedded 8 Industry Pro": "8",
  822. "Windows POSReady 7": "7",
  823. "Windows Embedded Standard 7": "7",
  824. "Windows Embedded POSReady 2009": "2009",
  825. "Windows Embedded Standard 2009": "2009",
  826. "Windows XP Embedded": "XP",
  827. }
  828. for caption in embedded_versions:
  829. version = core._windows_os_release_grain(caption, 1)
  830. self.assertEqual(
  831. version,
  832. embedded_versions[caption],
  833. "{0} != {1}\n"
  834. "version: {0}\n"
  835. "found: {1}\n"
  836. "caption: {2}".format(version, embedded_versions[caption], caption),
  837. )
  838. # Special Cases
  839. # Windows Embedded Standard is Windows 7
  840. caption = "Windows Embedded Standard"
  841. with patch("platform.release", MagicMock(return_value="7")):
  842. version = core._windows_os_release_grain(caption, 1)
  843. self.assertEqual(version, "7")
  844. # Microsoft Hyper-V Server 2019
  845. # Issue https://github.com/saltstack/salt/issue/55212
  846. caption = "Microsoft Hyper-V Server"
  847. version = core._windows_os_release_grain(caption, 1)
  848. self.assertEqual(version, "2019Server")
  849. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  850. def test_linux_memdata(self):
  851. """
  852. Test memdata on Linux systems
  853. """
  854. _proc_meminfo = textwrap.dedent(
  855. """\
  856. MemTotal: 16277028 kB
  857. SwapTotal: 4789244 kB"""
  858. )
  859. with patch("salt.utils.files.fopen", mock_open(read_data=_proc_meminfo)):
  860. memdata = core._linux_memdata()
  861. self.assertEqual(memdata.get("mem_total"), 15895)
  862. self.assertEqual(memdata.get("swap_total"), 4676)
  863. @skipIf(salt.utils.platform.is_windows(), "System is Windows")
  864. def test_bsd_memdata(self):
  865. """
  866. Test to memdata on *BSD systems
  867. """
  868. _path_exists_map = {}
  869. _path_isfile_map = {}
  870. _cmd_run_map = {
  871. "freebsd-version -u": "10.3-RELEASE",
  872. "/sbin/sysctl -n hw.physmem": "2121781248",
  873. "/sbin/sysctl -n vm.swap_total": "419430400",
  874. }
  875. path_exists_mock = MagicMock(side_effect=lambda x: _path_exists_map[x])
  876. path_isfile_mock = MagicMock(
  877. side_effect=lambda x: _path_isfile_map.get(x, False)
  878. )
  879. cmd_run_mock = MagicMock(side_effect=lambda x: _cmd_run_map[x])
  880. empty_mock = MagicMock(return_value={})
  881. mock_freebsd_uname = (
  882. "FreeBSD",
  883. "freebsd10.3-hostname-8148",
  884. "10.3-RELEASE",
  885. "FreeBSD 10.3-RELEASE #0 r297264: Fri Mar 25 02:10:02 UTC 2016 root@releng1.nyi.freebsd.org:/usr/obj/usr/src/sys/GENERIC",
  886. "amd64",
  887. "amd64",
  888. )
  889. with patch("platform.uname", MagicMock(return_value=mock_freebsd_uname)):
  890. with patch.object(
  891. salt.utils.platform, "is_linux", MagicMock(return_value=False)
  892. ):
  893. with patch.object(
  894. salt.utils.platform, "is_freebsd", MagicMock(return_value=True)
  895. ):
  896. # Skip the first if statement
  897. with patch.object(
  898. salt.utils.platform, "is_proxy", MagicMock(return_value=False)
  899. ):
  900. # Skip the init grain compilation (not pertinent)
  901. with patch.object(os.path, "exists", path_exists_mock):
  902. with patch("salt.utils.path.which") as mock:
  903. mock.return_value = "/sbin/sysctl"
  904. # Make a bunch of functions return empty dicts,
  905. # we don't care about these grains for the
  906. # purposes of this test.
  907. with patch.object(core, "_bsd_cpudata", empty_mock):
  908. with patch.object(core, "_hw_data", empty_mock):
  909. with patch.object(core, "_virtual", empty_mock):
  910. with patch.object(core, "_ps", empty_mock):
  911. # Mock the osarch
  912. with patch.dict(
  913. core.__salt__,
  914. {"cmd.run": cmd_run_mock},
  915. ):
  916. os_grains = core.os_data()
  917. self.assertEqual(os_grains.get("mem_total"), 2023)
  918. self.assertEqual(os_grains.get("swap_total"), 400)
  919. @skipIf(salt.utils.platform.is_windows(), "System is Windows")
  920. def test_docker_virtual(self):
  921. """
  922. Test if virtual grains are parsed correctly in Docker.
  923. """
  924. with patch.object(os.path, "isdir", MagicMock(return_value=False)):
  925. with patch.object(
  926. os.path,
  927. "isfile",
  928. MagicMock(
  929. side_effect=lambda x: True if x == "/proc/1/cgroup" else False
  930. ),
  931. ):
  932. for cgroup_substr in (
  933. ":/system.slice/docker",
  934. ":/docker/",
  935. ":/docker-ce/",
  936. ):
  937. cgroup_data = "10:memory{0}a_long_sha256sum".format(cgroup_substr)
  938. log.debug("Testing Docker cgroup substring '%s'", cgroup_substr)
  939. with patch(
  940. "salt.utils.files.fopen", mock_open(read_data=cgroup_data)
  941. ):
  942. with patch.dict(core.__salt__, {"cmd.run_all": MagicMock()}):
  943. grains = core._virtual({"kernel": "Linux"})
  944. self.assertEqual(grains.get("virtual_subtype"), "Docker")
  945. self.assertEqual(
  946. grains.get("virtual"), "container",
  947. )
  948. @skipIf(salt.utils.platform.is_windows(), "System is Windows")
  949. def test_lxc_virtual(self):
  950. """
  951. Test if virtual grains are parsed correctly in LXC.
  952. """
  953. with patch.object(os.path, "isdir", MagicMock(return_value=False)):
  954. with patch.object(
  955. os.path,
  956. "isfile",
  957. MagicMock(
  958. side_effect=lambda x: True if x == "/proc/1/cgroup" else False
  959. ),
  960. ):
  961. cgroup_data = "10:memory:/lxc/a_long_sha256sum"
  962. with patch("salt.utils.files.fopen", mock_open(read_data=cgroup_data)):
  963. with patch.dict(core.__salt__, {"cmd.run_all": MagicMock()}):
  964. grains = core._virtual({"kernel": "Linux"})
  965. self.assertEqual(grains.get("virtual_subtype"), "LXC")
  966. self.assertEqual(
  967. grains.get("virtual"), "container",
  968. )
  969. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  970. def test_xen_virtual(self):
  971. """
  972. Test if OS grains are parsed correctly in Ubuntu Xenial Xerus
  973. """
  974. with patch.multiple(
  975. os.path,
  976. isdir=MagicMock(side_effect=lambda x: x == "/sys/bus/xen"),
  977. isfile=MagicMock(
  978. side_effect=lambda x: x == "/sys/bus/xen/drivers/xenconsole"
  979. ),
  980. ):
  981. with patch.dict(core.__salt__, {"cmd.run": MagicMock(return_value="")}):
  982. log.debug("Testing Xen")
  983. self.assertEqual(
  984. core._virtual({"kernel": "Linux"}).get("virtual_subtype"),
  985. "Xen PV DomU",
  986. )
  987. @skipIf(salt.utils.platform.is_windows(), "System is Windows")
  988. def test_illumos_virtual(self):
  989. """
  990. Test if virtual grains are parsed correctly inside illumos/solaris zone
  991. """
  992. def _cmd_side_effect(cmd):
  993. if cmd == "/usr/bin/zonename":
  994. # NOTE: we return the name of the zone
  995. return "myzone"
  996. log.debug("cmd.run: '{}'".format(cmd))
  997. def _cmd_all_side_effect(cmd):
  998. # NOTE: prtdiag doesn't work inside a zone
  999. # so we return the expected result
  1000. if cmd == "/usr/sbin/prtdiag ":
  1001. return {
  1002. "pid": 32208,
  1003. "retcode": 1,
  1004. "stdout": "",
  1005. "stderr": "prtdiag can only be run in the global zone",
  1006. }
  1007. log.debug("cmd.run_all: '{}'".format(cmd))
  1008. def _which_side_effect(path):
  1009. if path == "prtdiag":
  1010. return "/usr/sbin/prtdiag"
  1011. elif path == "zonename":
  1012. return "/usr/bin/zonename"
  1013. return None
  1014. with patch.dict(
  1015. core.__salt__,
  1016. {
  1017. "cmd.run": MagicMock(side_effect=_cmd_side_effect),
  1018. "cmd.run_all": MagicMock(side_effect=_cmd_all_side_effect),
  1019. },
  1020. ):
  1021. with patch(
  1022. "salt.utils.path.which", MagicMock(side_effect=_which_side_effect)
  1023. ):
  1024. grains = core._virtual({"kernel": "SunOS"})
  1025. self.assertEqual(
  1026. grains.get("virtual"), "zone",
  1027. )
  1028. @skipIf(salt.utils.platform.is_windows(), "System is Windows")
  1029. def test_illumos_fallback_virtual(self):
  1030. """
  1031. Test if virtual grains are parsed correctly inside illumos/solaris zone
  1032. """
  1033. def _cmd_all_side_effect(cmd):
  1034. # NOTE: prtdiag doesn't work inside a zone
  1035. # so we return the expected result
  1036. if cmd == "/usr/sbin/prtdiag ":
  1037. return {
  1038. "pid": 32208,
  1039. "retcode": 1,
  1040. "stdout": "",
  1041. "stderr": "prtdiag can only be run in the global zone",
  1042. }
  1043. log.debug("cmd.run_all: '{}'".format(cmd))
  1044. def _which_side_effect(path):
  1045. if path == "prtdiag":
  1046. return "/usr/sbin/prtdiag"
  1047. return None
  1048. def _isdir_side_effect(path):
  1049. if path == "/.SUNWnative":
  1050. return True
  1051. return False
  1052. with patch.dict(
  1053. core.__salt__, {"cmd.run_all": MagicMock(side_effect=_cmd_all_side_effect)},
  1054. ):
  1055. with patch(
  1056. "salt.utils.path.which", MagicMock(side_effect=_which_side_effect)
  1057. ):
  1058. with patch("os.path.isdir", MagicMock(side_effect=_isdir_side_effect)):
  1059. grains = core._virtual({"kernel": "SunOS"})
  1060. self.assertEqual(
  1061. grains.get("virtual"), "zone",
  1062. )
  1063. def test_if_virtual_subtype_exists_virtual_should_fallback_to_virtual(self):
  1064. def mockstat(path):
  1065. if path == "/":
  1066. return "fnord"
  1067. elif path == "/proc/1/root/.":
  1068. return "roscivs"
  1069. return None
  1070. with patch.dict(
  1071. core.__salt__,
  1072. {
  1073. "cmd.run": MagicMock(return_value=""),
  1074. "cmd.run_all": MagicMock(return_value={"retcode": 0, "stdout": ""}),
  1075. },
  1076. ):
  1077. with patch.multiple(
  1078. os.path,
  1079. isfile=MagicMock(return_value=False),
  1080. isdir=MagicMock(side_effect=lambda x: x == "/proc"),
  1081. ):
  1082. with patch.multiple(
  1083. os, stat=MagicMock(side_effect=mockstat),
  1084. ):
  1085. grains = core._virtual({"kernel": "Linux"})
  1086. assert grains.get("virtual_subtype") is not None
  1087. assert grains.get("virtual") == "virtual"
  1088. def _check_ipaddress(self, value, ip_v):
  1089. """
  1090. check if ip address in a list is valid
  1091. """
  1092. for val in value:
  1093. assert isinstance(val, six.string_types)
  1094. ip_method = "is_ipv{0}".format(ip_v)
  1095. self.assertTrue(getattr(salt.utils.network, ip_method)(val))
  1096. def _check_empty(self, key, value, empty):
  1097. """
  1098. if empty is False and value does not exist assert error
  1099. if empty is True and value exists assert error
  1100. """
  1101. if not empty and not value:
  1102. raise Exception("{0} is empty, expecting a value".format(key))
  1103. elif empty and value:
  1104. raise Exception(
  1105. "{0} is suppose to be empty. value: {1} \
  1106. exists".format(
  1107. key, value
  1108. )
  1109. )
  1110. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  1111. def test_fqdn_return(self):
  1112. """
  1113. test ip4 and ip6 return values
  1114. """
  1115. net_ip4_mock = [IP4_LOCAL, IP4_ADD1, IP4_ADD2]
  1116. net_ip6_mock = [IP6_LOCAL, IP6_ADD1, IP6_ADD2]
  1117. self._run_fqdn_tests(
  1118. net_ip4_mock, net_ip6_mock, ip4_empty=False, ip6_empty=False
  1119. )
  1120. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  1121. def test_fqdn6_empty(self):
  1122. """
  1123. test when ip6 is empty
  1124. """
  1125. net_ip4_mock = [IP4_LOCAL, IP4_ADD1, IP4_ADD2]
  1126. net_ip6_mock = []
  1127. self._run_fqdn_tests(net_ip4_mock, net_ip6_mock, ip4_empty=False)
  1128. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  1129. def test_fqdn4_empty(self):
  1130. """
  1131. test when ip4 is empty
  1132. """
  1133. net_ip4_mock = []
  1134. net_ip6_mock = [IP6_LOCAL, IP6_ADD1, IP6_ADD2]
  1135. self._run_fqdn_tests(net_ip4_mock, net_ip6_mock, ip6_empty=False)
  1136. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  1137. def test_fqdn_all_empty(self):
  1138. """
  1139. test when both ip4 and ip6 are empty
  1140. """
  1141. net_ip4_mock = []
  1142. net_ip6_mock = []
  1143. self._run_fqdn_tests(net_ip4_mock, net_ip6_mock)
  1144. def _run_fqdn_tests(
  1145. self, net_ip4_mock, net_ip6_mock, ip6_empty=True, ip4_empty=True
  1146. ):
  1147. def _check_type(key, value, ip4_empty, ip6_empty):
  1148. """
  1149. check type and other checks
  1150. """
  1151. assert isinstance(value, list)
  1152. if "4" in key:
  1153. self._check_empty(key, value, ip4_empty)
  1154. self._check_ipaddress(value, ip_v="4")
  1155. elif "6" in key:
  1156. self._check_empty(key, value, ip6_empty)
  1157. self._check_ipaddress(value, ip_v="6")
  1158. ip4_mock = [(2, 1, 6, "", (IP4_ADD1, 0)), (2, 3, 0, "", (IP4_ADD2, 0))]
  1159. ip6_mock = [
  1160. (10, 1, 6, "", (IP6_ADD1, 0, 0, 0)),
  1161. (10, 3, 0, "", (IP6_ADD2, 0, 0, 0)),
  1162. ]
  1163. with patch.dict(core.__opts__, {"ipv6": False}):
  1164. with patch.object(
  1165. salt.utils.network, "ip_addrs", MagicMock(return_value=net_ip4_mock)
  1166. ):
  1167. with patch.object(
  1168. salt.utils.network,
  1169. "ip_addrs6",
  1170. MagicMock(return_value=net_ip6_mock),
  1171. ):
  1172. with patch.object(
  1173. core.socket, "getaddrinfo", side_effect=[ip4_mock, ip6_mock]
  1174. ):
  1175. get_fqdn = core.ip_fqdn()
  1176. ret_keys = ["fqdn_ip4", "fqdn_ip6", "ipv4", "ipv6"]
  1177. for key in ret_keys:
  1178. value = get_fqdn[key]
  1179. _check_type(key, value, ip4_empty, ip6_empty)
  1180. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  1181. @patch.object(salt.utils.platform, "is_windows", MagicMock(return_value=False))
  1182. @patch("salt.grains.core.__opts__", {"ipv6": False})
  1183. def test_dns_return(self):
  1184. """
  1185. test the return for a dns grain. test for issue:
  1186. https://github.com/saltstack/salt/issues/41230
  1187. """
  1188. resolv_mock = {
  1189. "domain": "",
  1190. "sortlist": [],
  1191. "nameservers": [
  1192. ipaddress.IPv4Address(IP4_ADD1),
  1193. ipaddress.IPv6Address(IP6_ADD1),
  1194. IP6_ADD_SCOPE,
  1195. ],
  1196. "ip4_nameservers": [ipaddress.IPv4Address(IP4_ADD1)],
  1197. "search": ["test.saltstack.com"],
  1198. "ip6_nameservers": [ipaddress.IPv6Address(IP6_ADD1), IP6_ADD_SCOPE],
  1199. "options": [],
  1200. }
  1201. ret = {
  1202. "dns": {
  1203. "domain": "",
  1204. "sortlist": [],
  1205. "nameservers": [IP4_ADD1, IP6_ADD1, IP6_ADD_SCOPE],
  1206. "ip4_nameservers": [IP4_ADD1],
  1207. "search": ["test.saltstack.com"],
  1208. "ip6_nameservers": [IP6_ADD1, IP6_ADD_SCOPE],
  1209. "options": [],
  1210. }
  1211. }
  1212. with patch.object(
  1213. salt.utils.dns, "parse_resolv", MagicMock(return_value=resolv_mock)
  1214. ):
  1215. assert core.dns() == ret
  1216. def test_enable_fqdns_false(self):
  1217. """
  1218. tests enable_fqdns_grains is set to False
  1219. """
  1220. with patch.dict("salt.grains.core.__opts__", {"enable_fqdns_grains": False}):
  1221. assert core.fqdns() == {"fqdns": []}
  1222. def test_enable_fqdns_true(self):
  1223. """
  1224. testing that grains uses network.fqdns module
  1225. """
  1226. with patch.dict(
  1227. "salt.grains.core.__salt__",
  1228. {"network.fqdns": MagicMock(return_value="my.fake.domain")},
  1229. ):
  1230. with patch.dict("salt.grains.core.__opts__", {"enable_fqdns_grains": True}):
  1231. assert core.fqdns() == "my.fake.domain"
  1232. def test_enable_fqdns_none(self):
  1233. """
  1234. testing default fqdns grains is returned when enable_fqdns_grains is None
  1235. """
  1236. with patch.dict("salt.grains.core.__opts__", {"enable_fqdns_grains": None}):
  1237. assert core.fqdns() == {"fqdns": []}
  1238. def test_enable_fqdns_without_patching(self):
  1239. """
  1240. testing fqdns grains is enabled by default
  1241. """
  1242. with patch.dict(
  1243. "salt.grains.core.__salt__",
  1244. {"network.fqdns": MagicMock(return_value="my.fake.domain")},
  1245. ):
  1246. # fqdns is disabled by default on Windows
  1247. if salt.utils.platform.is_windows():
  1248. assert core.fqdns() == {"fqdns": []}
  1249. else:
  1250. assert core.fqdns() == "my.fake.domain"
  1251. def test_enable_fqdns_false_is_proxy(self):
  1252. """
  1253. testing fqdns grains is disabled by default for proxy minions
  1254. """
  1255. with patch("salt.utils.platform.is_proxy", return_value=True, autospec=True):
  1256. with patch.dict(
  1257. "salt.grains.core.__salt__",
  1258. {"network.fqdns": MagicMock(return_value="my.fake.domain")},
  1259. ):
  1260. # fqdns is disabled by default on proxy minions
  1261. assert core.fqdns() == {"fqdns": []}
  1262. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  1263. @patch(
  1264. "salt.utils.network.ip_addrs", MagicMock(return_value=["1.2.3.4", "5.6.7.8"])
  1265. )
  1266. @patch(
  1267. "salt.utils.network.ip_addrs6",
  1268. MagicMock(return_value=["fe80::a8b2:93ff:fe00:0", "fe80::a8b2:93ff:dead:beef"]),
  1269. )
  1270. @patch(
  1271. "salt.utils.network.socket.getfqdn", MagicMock(side_effect=lambda v: v)
  1272. ) # Just pass-through
  1273. def test_fqdns_return(self):
  1274. """
  1275. test the return for a dns grain. test for issue:
  1276. https://github.com/saltstack/salt/issues/41230
  1277. """
  1278. reverse_resolv_mock = [
  1279. ("foo.bar.baz", [], ["1.2.3.4"]),
  1280. ("rinzler.evil-corp.com", [], ["5.6.7.8"]),
  1281. ("foo.bar.baz", [], ["fe80::a8b2:93ff:fe00:0"]),
  1282. ("bluesniff.foo.bar", [], ["fe80::a8b2:93ff:dead:beef"]),
  1283. ]
  1284. ret = {"fqdns": ["bluesniff.foo.bar", "foo.bar.baz", "rinzler.evil-corp.com"]}
  1285. with patch.dict(core.__salt__, {"network.fqdns": salt.modules.network.fqdns}):
  1286. with patch.object(socket, "gethostbyaddr", side_effect=reverse_resolv_mock):
  1287. fqdns = core.fqdns()
  1288. assert "fqdns" in fqdns
  1289. assert len(fqdns["fqdns"]) == len(ret["fqdns"])
  1290. assert set(fqdns["fqdns"]) == set(ret["fqdns"])
  1291. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  1292. @patch("salt.utils.network.ip_addrs", MagicMock(return_value=["1.2.3.4"]))
  1293. @patch("salt.utils.network.ip_addrs6", MagicMock(return_value=[]))
  1294. def test_fqdns_socket_error(self):
  1295. """
  1296. test the behavior on non-critical socket errors of the dns grain
  1297. """
  1298. def _gen_gethostbyaddr(errno):
  1299. def _gethostbyaddr(_):
  1300. herror = socket.herror()
  1301. herror.errno = errno
  1302. raise herror
  1303. return _gethostbyaddr
  1304. for errno in (0, core.HOST_NOT_FOUND, core.NO_DATA):
  1305. mock_log = MagicMock()
  1306. with patch.dict(
  1307. core.__salt__, {"network.fqdns": salt.modules.network.fqdns}
  1308. ):
  1309. with patch.object(
  1310. socket, "gethostbyaddr", side_effect=_gen_gethostbyaddr(errno)
  1311. ):
  1312. with patch("salt.modules.network.log", mock_log):
  1313. self.assertEqual(core.fqdns(), {"fqdns": []})
  1314. mock_log.debug.assert_called()
  1315. mock_log.error.assert_not_called()
  1316. mock_log = MagicMock()
  1317. with patch.dict(core.__salt__, {"network.fqdns": salt.modules.network.fqdns}):
  1318. with patch.object(
  1319. socket, "gethostbyaddr", side_effect=_gen_gethostbyaddr(-1)
  1320. ):
  1321. with patch("salt.modules.network.log", mock_log):
  1322. self.assertEqual(core.fqdns(), {"fqdns": []})
  1323. mock_log.debug.assert_called_once()
  1324. mock_log.error.assert_called()
  1325. def test_core_virtual(self):
  1326. """
  1327. test virtual grain with cmd virt-what
  1328. """
  1329. virt = "kvm"
  1330. with patch.object(
  1331. salt.utils.platform, "is_windows", MagicMock(return_value=False)
  1332. ):
  1333. with patch.object(salt.utils.path, "which", MagicMock(return_value=True)):
  1334. with patch.dict(
  1335. core.__salt__,
  1336. {
  1337. "cmd.run_all": MagicMock(
  1338. return_value={
  1339. "pid": 78,
  1340. "retcode": 0,
  1341. "stderr": "",
  1342. "stdout": virt,
  1343. }
  1344. )
  1345. },
  1346. ):
  1347. osdata = {
  1348. "kernel": "test",
  1349. }
  1350. ret = core._virtual(osdata)
  1351. self.assertEqual(ret["virtual"], virt)
  1352. with patch.dict(
  1353. core.__salt__,
  1354. {
  1355. "cmd.run_all": MagicMock(
  1356. return_value={
  1357. "pid": 78,
  1358. "retcode": 0,
  1359. "stderr": "",
  1360. "stdout": "\n\n{0}".format(virt),
  1361. }
  1362. )
  1363. },
  1364. ):
  1365. osdata = {
  1366. "kernel": "test",
  1367. }
  1368. ret = core._virtual(osdata)
  1369. self.assertEqual(ret["virtual"], virt)
  1370. def test_solaris_sparc_s7zone(self):
  1371. """
  1372. verify productname grain for s7 zone
  1373. """
  1374. expectation = {
  1375. "productname": "SPARC S7-2",
  1376. "product": "SPARC S7-2",
  1377. }
  1378. with salt.utils.files.fopen(
  1379. os.path.join(SOLARIS_DIR, "prtconf.s7-zone")
  1380. ) as sparc_return_data:
  1381. this_sparc_return_data = "\n".join(sparc_return_data.readlines())
  1382. this_sparc_return_data += "\n"
  1383. self._check_solaris_sparc_productname_grains(
  1384. this_sparc_return_data, expectation
  1385. )
  1386. def test_solaris_sparc_s7(self):
  1387. """
  1388. verify productname grain for s7
  1389. """
  1390. expectation = {
  1391. "productname": "SPARC S7-2",
  1392. "product": "SPARC S7-2",
  1393. }
  1394. with salt.utils.files.fopen(
  1395. os.path.join(SOLARIS_DIR, "prtdiag.s7")
  1396. ) as sparc_return_data:
  1397. this_sparc_return_data = "\n".join(sparc_return_data.readlines())
  1398. this_sparc_return_data += "\n"
  1399. self._check_solaris_sparc_productname_grains(
  1400. this_sparc_return_data, expectation
  1401. )
  1402. def test_solaris_sparc_t5220(self):
  1403. """
  1404. verify productname grain for t5220
  1405. """
  1406. expectation = {
  1407. "productname": "SPARC Enterprise T5220",
  1408. "product": "SPARC Enterprise T5220",
  1409. }
  1410. with salt.utils.files.fopen(
  1411. os.path.join(SOLARIS_DIR, "prtdiag.t5220")
  1412. ) as sparc_return_data:
  1413. this_sparc_return_data = "\n".join(sparc_return_data.readlines())
  1414. this_sparc_return_data += "\n"
  1415. self._check_solaris_sparc_productname_grains(
  1416. this_sparc_return_data, expectation
  1417. )
  1418. def test_solaris_sparc_t5220zone(self):
  1419. """
  1420. verify productname grain for t5220 zone
  1421. """
  1422. expectation = {
  1423. "productname": "SPARC Enterprise T5220",
  1424. "product": "SPARC Enterprise T5220",
  1425. }
  1426. with salt.utils.files.fopen(
  1427. os.path.join(SOLARIS_DIR, "prtconf.t5220-zone")
  1428. ) as sparc_return_data:
  1429. this_sparc_return_data = "\n".join(sparc_return_data.readlines())
  1430. this_sparc_return_data += "\n"
  1431. self._check_solaris_sparc_productname_grains(
  1432. this_sparc_return_data, expectation
  1433. )
  1434. def _check_solaris_sparc_productname_grains(self, prtdata, expectation):
  1435. """
  1436. verify product grains on solaris sparc
  1437. """
  1438. import platform
  1439. path_isfile_mock = MagicMock(side_effect=lambda x: x in ["/etc/release"])
  1440. with salt.utils.files.fopen(
  1441. os.path.join(OS_RELEASE_DIR, "solaris-11.3")
  1442. ) as os_release_file:
  1443. os_release_content = os_release_file.readlines()
  1444. uname_mock = MagicMock(
  1445. return_value=("SunOS", "testsystem", "5.11", "11.3", "sunv4", "sparc")
  1446. )
  1447. with patch.object(platform, "uname", uname_mock), patch.object(
  1448. salt.utils.platform, "is_proxy", MagicMock(return_value=False)
  1449. ), patch.object(
  1450. salt.utils.platform, "is_linux", MagicMock(return_value=False)
  1451. ), patch.object(
  1452. salt.utils.platform, "is_windows", MagicMock(return_value=False)
  1453. ), patch.object(
  1454. salt.utils.platform, "is_smartos", MagicMock(return_value=False)
  1455. ), patch.object(
  1456. salt.utils.path, "which_bin", MagicMock(return_value=None)
  1457. ), patch.object(
  1458. os.path, "isfile", path_isfile_mock
  1459. ), patch(
  1460. "salt.utils.files.fopen", mock_open(read_data=os_release_content)
  1461. ) as os_release_file, patch.object(
  1462. core,
  1463. "_sunos_cpudata",
  1464. MagicMock(
  1465. return_value={
  1466. "cpuarch": "sparcv9",
  1467. "num_cpus": "1",
  1468. "cpu_model": "MOCK_CPU_MODEL",
  1469. "cpu_flags": [],
  1470. }
  1471. ),
  1472. ), patch.object(
  1473. core, "_memdata", MagicMock(return_value={"mem_total": 16384})
  1474. ), patch.object(
  1475. core, "_virtual", MagicMock(return_value={})
  1476. ), patch.object(
  1477. core, "_ps", MagicMock(return_value={})
  1478. ), patch.object(
  1479. salt.utils.path, "which", MagicMock(return_value=True)
  1480. ), patch.dict(
  1481. core.__salt__, {"cmd.run": MagicMock(return_value=prtdata)}
  1482. ):
  1483. os_grains = core.os_data()
  1484. grains = {
  1485. k: v for k, v in os_grains.items() if k in set(["product", "productname"])
  1486. }
  1487. self.assertEqual(grains, expectation)
  1488. @patch("os.path.isfile")
  1489. @patch("os.path.isdir")
  1490. def test_core_virtual_unicode(self, mock_file, mock_dir):
  1491. """
  1492. test virtual grain with unicode character in product_name file
  1493. """
  1494. def path_side_effect(path):
  1495. if path == "/sys/devices/virtual/dmi/id/product_name":
  1496. return True
  1497. return False
  1498. virt = "kvm"
  1499. mock_file.side_effect = path_side_effect
  1500. mock_dir.side_effect = path_side_effect
  1501. with patch.object(
  1502. salt.utils.platform, "is_windows", MagicMock(return_value=False)
  1503. ):
  1504. with patch.object(salt.utils.path, "which", MagicMock(return_value=True)):
  1505. with patch.dict(
  1506. core.__salt__,
  1507. {
  1508. "cmd.run_all": MagicMock(
  1509. return_value={
  1510. "pid": 78,
  1511. "retcode": 0,
  1512. "stderr": "",
  1513. "stdout": virt,
  1514. }
  1515. )
  1516. },
  1517. ):
  1518. with patch("salt.utils.files.fopen", mock_open(read_data="嗨")):
  1519. osdata = {
  1520. "kernel": "Linux",
  1521. }
  1522. ret = core._virtual(osdata)
  1523. self.assertEqual(ret["virtual"], virt)
  1524. @patch("salt.utils.path.which", MagicMock(return_value="/usr/sbin/sysctl"))
  1525. def test_osx_memdata_with_comma(self):
  1526. """
  1527. test osx memdata method when comma returns
  1528. """
  1529. def _cmd_side_effect(cmd):
  1530. if "hw.memsize" in cmd:
  1531. return "4294967296"
  1532. elif "vm.swapusage" in cmd:
  1533. return "total = 1024,00M used = 160,75M free = 863,25M (encrypted)"
  1534. with patch.dict(
  1535. core.__salt__, {"cmd.run": MagicMock(side_effect=_cmd_side_effect)}
  1536. ):
  1537. ret = core._osx_memdata()
  1538. assert ret["swap_total"] == 1024
  1539. assert ret["mem_total"] == 4096
  1540. @patch("salt.utils.path.which", MagicMock(return_value="/usr/sbin/sysctl"))
  1541. def test_osx_memdata(self):
  1542. """
  1543. test osx memdata
  1544. """
  1545. def _cmd_side_effect(cmd):
  1546. if "hw.memsize" in cmd:
  1547. return "4294967296"
  1548. elif "vm.swapusage" in cmd:
  1549. return "total = 0.00M used = 0.00M free = 0.00M (encrypted)"
  1550. with patch.dict(
  1551. core.__salt__, {"cmd.run": MagicMock(side_effect=_cmd_side_effect)}
  1552. ):
  1553. ret = core._osx_memdata()
  1554. assert ret["swap_total"] == 0
  1555. assert ret["mem_total"] == 4096
  1556. @skipIf(not core._DATEUTIL_TZ, "Missing dateutil.tz")
  1557. def test_locale_info_tzname(self):
  1558. # mock datetime.now().tzname()
  1559. # cant just mock now because it is read only
  1560. tzname = Mock(return_value="MDT_FAKE")
  1561. now_ret_object = Mock(tzname=tzname)
  1562. now = Mock(return_value=now_ret_object)
  1563. datetime = Mock(now=now)
  1564. with patch.object(core, "datetime", datetime=datetime) as datetime_module:
  1565. with patch.object(
  1566. core.dateutil.tz, "tzlocal", return_value=object
  1567. ) as tzlocal:
  1568. with patch.object(
  1569. salt.utils.platform, "is_proxy", return_value=False
  1570. ) as is_proxy:
  1571. ret = core.locale_info()
  1572. tzname.assert_called_once_with()
  1573. self.assertEqual(len(now_ret_object.method_calls), 1)
  1574. now.assert_called_once_with(object)
  1575. self.assertEqual(len(datetime.method_calls), 1)
  1576. self.assertEqual(len(datetime_module.method_calls), 1)
  1577. tzlocal.assert_called_once_with()
  1578. is_proxy.assert_called_once_with()
  1579. self.assertEqual(ret["locale_info"]["timezone"], "MDT_FAKE")
  1580. @skipIf(not core._DATEUTIL_TZ, "Missing dateutil.tz")
  1581. def test_locale_info_unicode_error_tzname(self):
  1582. # UnicodeDecodeError most have the default string encoding
  1583. unicode_error = UnicodeDecodeError(str("fake"), b"\x00\x00", 1, 2, str("fake"))
  1584. # mock datetime.now().tzname()
  1585. # cant just mock now because it is read only
  1586. tzname = Mock(return_value="MDT_FAKE")
  1587. now_ret_object = Mock(tzname=tzname)
  1588. now = Mock(return_value=now_ret_object)
  1589. datetime = Mock(now=now)
  1590. # mock tzname[0].decode()
  1591. decode = Mock(return_value="CST_FAKE")
  1592. tzname2 = (Mock(decode=decode,),)
  1593. with patch.object(core, "datetime", datetime=datetime) as datetime_module:
  1594. with patch.object(
  1595. core.dateutil.tz, "tzlocal", side_effect=unicode_error
  1596. ) as tzlocal:
  1597. with patch.object(
  1598. salt.utils.platform, "is_proxy", return_value=False
  1599. ) as is_proxy:
  1600. with patch.object(
  1601. core.salt.utils.platform, "is_windows", return_value=True
  1602. ) as is_windows:
  1603. with patch.object(core, "time", tzname=tzname2):
  1604. ret = core.locale_info()
  1605. tzname.assert_not_called()
  1606. self.assertEqual(len(now_ret_object.method_calls), 0)
  1607. now.assert_not_called()
  1608. self.assertEqual(len(datetime.method_calls), 0)
  1609. decode.assert_called_once_with("mbcs")
  1610. self.assertEqual(len(tzname2[0].method_calls), 1)
  1611. self.assertEqual(len(datetime_module.method_calls), 0)
  1612. tzlocal.assert_called_once_with()
  1613. is_proxy.assert_called_once_with()
  1614. is_windows.assert_called_once_with()
  1615. self.assertEqual(ret["locale_info"]["timezone"], "CST_FAKE")
  1616. @skipIf(core._DATEUTIL_TZ, "Not Missing dateutil.tz")
  1617. def test_locale_info_no_tz_tzname(self):
  1618. with patch.object(
  1619. salt.utils.platform, "is_proxy", return_value=False
  1620. ) as is_proxy:
  1621. with patch.object(
  1622. core.salt.utils.platform, "is_windows", return_value=True
  1623. ) as is_windows:
  1624. ret = core.locale_info()
  1625. is_proxy.assert_called_once_with()
  1626. is_windows.assert_not_called()
  1627. self.assertEqual(ret["locale_info"]["timezone"], "unknown")
  1628. def test_cwd_exists(self):
  1629. cwd_grain = core.cwd()
  1630. self.assertIsInstance(cwd_grain, dict)
  1631. self.assertTrue("cwd" in cwd_grain)
  1632. self.assertEqual(cwd_grain["cwd"], os.getcwd())
  1633. def test_cwd_is_cwd(self):
  1634. cwd = os.getcwd()
  1635. try:
  1636. # change directory
  1637. new_dir = os.path.split(cwd)[0]
  1638. os.chdir(new_dir)
  1639. cwd_grain = core.cwd()
  1640. self.assertEqual(cwd_grain["cwd"], new_dir)
  1641. finally:
  1642. # change back to original directory
  1643. os.chdir(cwd)
  1644. def test_virtual_set_virtual_grain(self):
  1645. osdata = {}
  1646. (
  1647. osdata["kernel"],
  1648. osdata["nodename"],
  1649. osdata["kernelrelease"],
  1650. osdata["kernelversion"],
  1651. osdata["cpuarch"],
  1652. _,
  1653. ) = platform.uname()
  1654. with patch.dict(
  1655. core.__salt__,
  1656. {
  1657. "cmd.run": salt.modules.cmdmod.run,
  1658. "cmd.run_all": salt.modules.cmdmod.run_all,
  1659. "cmd.retcode": salt.modules.cmdmod.retcode,
  1660. "smbios.get": salt.modules.smbios.get,
  1661. },
  1662. ):
  1663. virtual_grains = core._virtual(osdata)
  1664. self.assertIn("virtual", virtual_grains)
  1665. def test_virtual_has_virtual_grain(self):
  1666. osdata = {"virtual": "something"}
  1667. (
  1668. osdata["kernel"],
  1669. osdata["nodename"],
  1670. osdata["kernelrelease"],
  1671. osdata["kernelversion"],
  1672. osdata["cpuarch"],
  1673. _,
  1674. ) = platform.uname()
  1675. with patch.dict(
  1676. core.__salt__,
  1677. {
  1678. "cmd.run": salt.modules.cmdmod.run,
  1679. "cmd.run_all": salt.modules.cmdmod.run_all,
  1680. "cmd.retcode": salt.modules.cmdmod.retcode,
  1681. "smbios.get": salt.modules.smbios.get,
  1682. },
  1683. ):
  1684. virtual_grains = core._virtual(osdata)
  1685. self.assertIn("virtual", virtual_grains)
  1686. self.assertNotEqual(virtual_grains["virtual"], "physical")
  1687. @skipIf(not salt.utils.platform.is_windows(), "System is not Windows")
  1688. def test_windows_virtual_set_virtual_grain(self):
  1689. osdata = {}
  1690. (
  1691. osdata["kernel"],
  1692. osdata["nodename"],
  1693. osdata["kernelrelease"],
  1694. osdata["kernelversion"],
  1695. osdata["cpuarch"],
  1696. _,
  1697. ) = platform.uname()
  1698. with patch.dict(
  1699. core.__salt__,
  1700. {
  1701. "cmd.run": salt.modules.cmdmod.run,
  1702. "cmd.run_all": salt.modules.cmdmod.run_all,
  1703. "cmd.retcode": salt.modules.cmdmod.retcode,
  1704. "smbios.get": salt.modules.smbios.get,
  1705. },
  1706. ):
  1707. virtual_grains = core._windows_virtual(osdata)
  1708. self.assertIn("virtual", virtual_grains)
  1709. @skipIf(not salt.utils.platform.is_windows(), "System is not Windows")
  1710. def test_windows_virtual_has_virtual_grain(self):
  1711. osdata = {"virtual": "something"}
  1712. (
  1713. osdata["kernel"],
  1714. osdata["nodename"],
  1715. osdata["kernelrelease"],
  1716. osdata["kernelversion"],
  1717. osdata["cpuarch"],
  1718. _,
  1719. ) = platform.uname()
  1720. with patch.dict(
  1721. core.__salt__,
  1722. {
  1723. "cmd.run": salt.modules.cmdmod.run,
  1724. "cmd.run_all": salt.modules.cmdmod.run_all,
  1725. "cmd.retcode": salt.modules.cmdmod.retcode,
  1726. "smbios.get": salt.modules.smbios.get,
  1727. },
  1728. ):
  1729. virtual_grains = core._windows_virtual(osdata)
  1730. self.assertIn("virtual", virtual_grains)
  1731. self.assertNotEqual(virtual_grains["virtual"], "physical")
  1732. @skipIf(not salt.utils.platform.is_windows(), "System is not Windows")
  1733. def test_osdata_virtual_key_win(self):
  1734. with patch.dict(
  1735. core.__salt__,
  1736. {
  1737. "cmd.run": salt.modules.cmdmod.run,
  1738. "cmd.run_all": salt.modules.cmdmod.run_all,
  1739. "cmd.retcode": salt.modules.cmdmod.retcode,
  1740. "smbios.get": salt.modules.smbios.get,
  1741. },
  1742. ):
  1743. _windows_platform_data_ret = core.os_data()
  1744. _windows_platform_data_ret["virtual"] = "something"
  1745. with patch.object(
  1746. core, "_windows_platform_data", return_value=_windows_platform_data_ret
  1747. ) as _windows_platform_data:
  1748. osdata_grains = core.os_data()
  1749. _windows_platform_data.assert_called_once()
  1750. self.assertIn("virtual", osdata_grains)
  1751. self.assertNotEqual(osdata_grains["virtual"], "physical")
  1752. @skipIf(salt.utils.platform.is_windows(), "System is Windows")
  1753. def test_bsd_osfullname(self):
  1754. """
  1755. Test to ensure osfullname exists on *BSD systems
  1756. """
  1757. _path_exists_map = {}
  1758. _path_isfile_map = {}
  1759. _cmd_run_map = {
  1760. "freebsd-version -u": "10.3-RELEASE",
  1761. "/sbin/sysctl -n hw.physmem": "2121781248",
  1762. "/sbin/sysctl -n vm.swap_total": "419430400",
  1763. }
  1764. path_exists_mock = MagicMock(side_effect=lambda x: _path_exists_map[x])
  1765. path_isfile_mock = MagicMock(
  1766. side_effect=lambda x: _path_isfile_map.get(x, False)
  1767. )
  1768. cmd_run_mock = MagicMock(side_effect=lambda x: _cmd_run_map[x])
  1769. empty_mock = MagicMock(return_value={})
  1770. mock_freebsd_uname = (
  1771. "FreeBSD",
  1772. "freebsd10.3-hostname-8148",
  1773. "10.3-RELEASE",
  1774. "FreeBSD 10.3-RELEASE #0 r297264: Fri Mar 25 02:10:02 UTC 2016 root@releng1.nyi.freebsd.org:/usr/obj/usr/src/sys/GENERIC",
  1775. "amd64",
  1776. "amd64",
  1777. )
  1778. with patch("platform.uname", MagicMock(return_value=mock_freebsd_uname)):
  1779. with patch.object(
  1780. salt.utils.platform, "is_linux", MagicMock(return_value=False)
  1781. ):
  1782. with patch.object(
  1783. salt.utils.platform, "is_freebsd", MagicMock(return_value=True)
  1784. ):
  1785. # Skip the first if statement
  1786. with patch.object(
  1787. salt.utils.platform, "is_proxy", MagicMock(return_value=False)
  1788. ):
  1789. # Skip the init grain compilation (not pertinent)
  1790. with patch.object(os.path, "exists", path_exists_mock):
  1791. with patch("salt.utils.path.which") as mock:
  1792. mock.return_value = "/sbin/sysctl"
  1793. # Make a bunch of functions return empty dicts,
  1794. # we don't care about these grains for the
  1795. # purposes of this test.
  1796. with patch.object(
  1797. core, "_bsd_cpudata", empty_mock
  1798. ), patch.object(
  1799. core, "_hw_data", empty_mock
  1800. ), patch.object(
  1801. core, "_virtual", empty_mock
  1802. ), patch.object(
  1803. core, "_ps", empty_mock
  1804. ), patch.dict(
  1805. core.__salt__, {"cmd.run": cmd_run_mock}
  1806. ):
  1807. os_grains = core.os_data()
  1808. self.assertIn("osfullname", os_grains)
  1809. self.assertEqual(os_grains.get("osfullname"), "FreeBSD")
  1810. def test_saltversioninfo(self):
  1811. """
  1812. test saltversioninfo core grain.
  1813. """
  1814. ret = core.saltversioninfo()
  1815. info = ret["saltversioninfo"]
  1816. assert isinstance(ret, dict)
  1817. assert isinstance(info, list)
  1818. try:
  1819. assert len(info) == 1
  1820. except AssertionError:
  1821. # We have a minor version we need to test
  1822. assert len(info) == 2
  1823. assert all([x is not None for x in info])
  1824. assert all([isinstance(x, int) for x in info])
  1825. def test_path(self):
  1826. comps = ["foo", "bar", "baz"]
  1827. path = os.path.pathsep.join(comps)
  1828. with patch.dict(os.environ, {"PATH": path}):
  1829. result = core.path()
  1830. assert result == {"path": path, "systempath": comps}, result
  1831. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  1832. @patch("os.path.exists")
  1833. @patch("salt.utils.platform.is_proxy")
  1834. def test__hw_data_linux_empty(self, is_proxy, exists):
  1835. is_proxy.return_value = False
  1836. exists.return_value = True
  1837. with patch("salt.utils.files.fopen", mock_open(read_data="")):
  1838. self.assertEqual(
  1839. core._hw_data({"kernel": "Linux"}),
  1840. {
  1841. "biosreleasedate": "",
  1842. "biosversion": "",
  1843. "manufacturer": "",
  1844. "productname": "",
  1845. "serialnumber": "",
  1846. "uuid": "",
  1847. },
  1848. )
  1849. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  1850. @patch("os.path.exists")
  1851. @patch("salt.utils.platform.is_proxy")
  1852. def test__hw_data_linux_unicode_error(self, is_proxy, exists):
  1853. def _fopen(*args):
  1854. class _File(object):
  1855. def __enter__(self):
  1856. return self
  1857. def __exit__(self, *args):
  1858. pass
  1859. def read(self):
  1860. raise UnicodeDecodeError("enconding", b"", 1, 2, "reason")
  1861. return _File()
  1862. is_proxy.return_value = False
  1863. exists.return_value = True
  1864. with patch("salt.utils.files.fopen", _fopen):
  1865. self.assertEqual(core._hw_data({"kernel": "Linux"}), {})
  1866. @skipIf(not salt.utils.platform.is_linux(), "System is not Linux")
  1867. def test_kernelparams_return(self):
  1868. expectations = [
  1869. (
  1870. "BOOT_IMAGE=/vmlinuz-3.10.0-693.2.2.el7.x86_64",
  1871. {
  1872. "kernelparams": [
  1873. ("BOOT_IMAGE", "/vmlinuz-3.10.0-693.2.2.el7.x86_64")
  1874. ]
  1875. },
  1876. ),
  1877. (
  1878. "root=/dev/mapper/centos_daemon-root",
  1879. {"kernelparams": [("root", "/dev/mapper/centos_daemon-root")]},
  1880. ),
  1881. (
  1882. "rhgb quiet ro",
  1883. {"kernelparams": [("rhgb", None), ("quiet", None), ("ro", None)]},
  1884. ),
  1885. ('param="value1"', {"kernelparams": [("param", "value1")]}),
  1886. (
  1887. 'param="value1 value2 value3"',
  1888. {"kernelparams": [("param", "value1 value2 value3")]},
  1889. ),
  1890. (
  1891. 'param="value1 value2 value3" LANG="pl" ro',
  1892. {
  1893. "kernelparams": [
  1894. ("param", "value1 value2 value3"),
  1895. ("LANG", "pl"),
  1896. ("ro", None),
  1897. ]
  1898. },
  1899. ),
  1900. ("ipv6.disable=1", {"kernelparams": [("ipv6.disable", "1")]}),
  1901. (
  1902. 'param="value1:value2:value3"',
  1903. {"kernelparams": [("param", "value1:value2:value3")]},
  1904. ),
  1905. (
  1906. 'param="value1,value2,value3"',
  1907. {"kernelparams": [("param", "value1,value2,value3")]},
  1908. ),
  1909. (
  1910. 'param="value1" param="value2" param="value3"',
  1911. {
  1912. "kernelparams": [
  1913. ("param", "value1"),
  1914. ("param", "value2"),
  1915. ("param", "value3"),
  1916. ]
  1917. },
  1918. ),
  1919. ]
  1920. for cmdline, expectation in expectations:
  1921. with patch("salt.utils.files.fopen", mock_open(read_data=cmdline)):
  1922. self.assertEqual(core.kernelparams(), expectation)
  1923. @patch("salt.utils.path.which", MagicMock(return_value="/usr/sbin/lspci"))
  1924. def test_linux_gpus(self):
  1925. """
  1926. Test GPU detection on Linux systems
  1927. """
  1928. def _cmd_side_effect(cmd):
  1929. ret = ""
  1930. for device in devices:
  1931. ret += textwrap.dedent(
  1932. """
  1933. Class: {0}
  1934. Vendor: {1}
  1935. Device: {2}
  1936. SVendor: Evil Corp.
  1937. SDevice: Graphics XXL
  1938. Rev: c1
  1939. NUMANode: 0"""
  1940. ).format(*device)
  1941. ret += "\n"
  1942. return ret.strip()
  1943. devices = [
  1944. [
  1945. "VGA compatible controller",
  1946. "Advanced Micro Devices, Inc. [AMD/ATI]",
  1947. "Vega [Radeon RX Vega]]",
  1948. "amd",
  1949. ], # AMD
  1950. [
  1951. "Audio device",
  1952. "Advanced Micro Devices, Inc. [AMD/ATI]",
  1953. "Device aaf8",
  1954. None,
  1955. ], # non-GPU device
  1956. [
  1957. "VGA compatible controller",
  1958. "NVIDIA Corporation",
  1959. "GK208 [GeForce GT 730]",
  1960. "nvidia",
  1961. ], # Nvidia
  1962. [
  1963. "VGA compatible controller",
  1964. "Intel Corporation",
  1965. "Device 5912",
  1966. "intel",
  1967. ], # Intel
  1968. [
  1969. "VGA compatible controller",
  1970. "ATI Technologies Inc",
  1971. "RC410 [Radeon Xpress 200M]",
  1972. "ati",
  1973. ], # ATI
  1974. [
  1975. "3D controller",
  1976. "NVIDIA Corporation",
  1977. "GeForce GTX 950M",
  1978. "nvidia",
  1979. ], # 3D controller
  1980. [
  1981. "Display controller",
  1982. "Intel Corporation",
  1983. "HD Graphics P630",
  1984. "intel",
  1985. ], # Display controller
  1986. ]
  1987. with patch.dict(
  1988. core.__salt__, {"cmd.run": MagicMock(side_effect=_cmd_side_effect)}
  1989. ):
  1990. ret = core._linux_gpu_data()["gpus"]
  1991. count = 0
  1992. for device in devices:
  1993. if device[3] is None:
  1994. continue
  1995. assert ret[count]["model"] == device[2]
  1996. assert ret[count]["vendor"] == device[3]
  1997. count += 1
  1998. def test_get_server_id(self):
  1999. expected = {"server_id": 94889706}
  2000. with patch.dict(core.__opts__, {"id": "anid"}):
  2001. assert core.get_server_id() == expected
  2002. with patch.dict(core.__opts__, {"id": "otherid"}):
  2003. assert core.get_server_id() != expected