Recent Entries 9
- pattern minor 112d agoSafely open a list of links in FirefoxI receive a list of links via http and I want to open them all in a new Firefox (or default browser) window as tabs; that is my script must not touch existing windows. This is the best solution I could come up with: ``` from subprocess import call links = GetListViaHTTP() if len(links) == 1: call(['firefox', '-new-window'] + links) elif len(links) > 1: call(['firefox'] + links) else: print('Nothing to do.') ``` This worked like a charm when I tested it, but putting something I received via http into `subprocess.call` does not look save to me at all. So the question is: How can I improve this code to avoid being vulnerable to MITM attacks? If the list was not tampered with by an attacker, all links it contains will point to Stack Overflow answers, so maybe somehow validating the links with `urllib.parse` is good enough?
- pattern minor 112d agoRecursively checking the css class of an iFrame ElementI am writing some tests in selenium webdriver (on node.js). and have made a custom function to check the css value of an iFrame Element. I'm a coding beginner. The script tests an app where the user writes the image width they want (just putting in a number) and the image in an iFrame should change width. This is tricky because one must switch iFrames, wait for elements to become stale (as the new image width is loaded) then grab the new element and check its css value. Often, the tests are flaky because sometimes it checks before the value has changed etc. I finally wrote a function that passed 120 times out of 120 times. ``` //function looks for 'el', then switches iframe and extracts the desired cssValur, then compares it to the 'value' we expect Page.checkCssValue = function (el, cssValue, value){ //find function, the '0' represents the iframe index var newEl = this.find(el, 0); return newEl.getCssValue(cssValue).then(function(result){ if(result !== value){ console.log(result + " and " + value + " Do not Match.") return Page.checkCssValue(el, cssValue, value); } else{ console.log(result + " and " + value + " Do Match!") return result; } }); }; ``` But I'm not sure if this is considered bad programming and if a while loop would be better?
- debug minor 112d agoError-testing be with cucumber/capybarawebI'm working on writing tests for a rails application using cucumber and capybara. I have a scenario for a user editing a post, and making it invalid. The scenario looks like this: `Scenario: I edit a post and make the data invalid. Given I have 1 post And I view my 1st post Then I click "Edit" And I fill in the edit post form with bad data When I click the "Update post" button Then I should see "Title is too short (minimum is 3 characters)" And I should see "Body is too short (minimum is 30 characters)" ` Should I leave the scenario as-is, or create a scenario for entering the title incorrectly, and another scenario for entering the body incorrectly, like this: `Scenario: I edit a post and make the title too short. Given I have 1 post And I view my 1st post Then I click "Edit" And I fill in the edit post form with a title that is too short When I click the "Update post" button Then I should see "Title is too short (minimum is 3 characters)" Scenario: I edit a post and make the body too short. Given I have 1 post And I view my 1st post Then I click "Edit" And I fill in the edit post form with a body that is too short When I click the "Update post" button Then I should see "Body is too short (minimum is 30 characters)" ` If the post has several more fields, should I still create a scenario for each one, or would it be more DRY to use one scenario?
- pattern minor 112d agoNewest Reddit submissions grabberMy program does exactly what I want it to do and it works well. However, I feel like it's very clunky. I'd like my code to be more efficient. By that I mean, I'd like it to accomplish what it already can, but in the best way possible and in the least amount of code. Basically, optimized. I'd also like it to be easily understandable. ``` using CefSharp; using CefSharp.WinForms; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using System.Windows.Forms; namespace Reddit_Newest_Submissions { public partial class Form1 : Form { private IList newestSubmissionsTitles; private IList newestSubmissionsURLs; private List filteredNewestSubmissionsTitles = new List(); private List filteredNewestSubmissionsURLs = new List(); private readonly ChromiumWebBrowser browser; public Form1() { InitializeComponent(); browser = new ChromiumWebBrowser("https://www.reddit.com/new/") { Dock = DockStyle.Fill }; browser.LoadingStateChanged += browser_LoadingStateChanged; panel1.Controls.Add(browser); } // javascript code that will return all of the newest submission's titles private const string getNewestSubmissionsTitlesScript = @"var newestSubmissionsTitles = []; for (i = 0; i browser.EvaluateScriptAsync(getNewestSubmissionsURLsScript).ContinueWith(b => { var aResponse = a.Result; var bResponse = b.Result; if (aResponse.Success && aResponse.Result != null && bResponse.Success && bResponse.Result != null) { //store the javascript response results into the according lists newestSubmissionsTitles = (IList)aResponse.Result; newestSubmissionsURLs = (IList)bResponse.R
- snippet minor 112d agoSelecting filter checkboxes using SeleniumI am using Selenium Webdriver via Java. My method clicks on a filter check box (eg. make, model, etc.), that is passed in, from a modal. When running my method in my test class, via ChromeDriver, it seems to go pretty slow and rightfully so since I am making a lot of tiny network calls for `getText()`. How can I optimize its performance? ``` public void selectFilter(String filter) { List filters = driver.findElements(selector.someWebElement()); Map mapFilters = new HashMap(); for (int i = 0; i < filters.size(); i++) { String key = filters.get(i).getText(); WebElement value = filters.get(i).findElement(By.cssSelector("a")); mapFilters.put(key, value); } mapFilters.get(filter).click(); } ```
- pattern moderate 112d agoChecking if text is NOT displayedI'm currently writing unit tests in Selenium (C#). I need to do two things in this particular test: Check if 2 errors (with html container) are displayed and check if another (given) error is not displayed. The test looks like this: ``` bool errorWindowVisible = tmethods.IsElementVisible(driver, By.XPath("//div[@class='message error']")); if (errorWindowVisible == false) { Assert.Fail("No error notification displayed."); } string errorTextTemp = "Error 1 text"; bool productIssue = tmethods.IsElementVisible(driver, By.XPath("//*[contains(.,'" + errorTextTemp + "')]")); errorTextTemp = "Error 2 text"; bool productIssueB = tmethods.IsElementVisible(driver, By.XPath("//*[contains(.,'" + errorTextTemp + "')]")); if (productIssue == false || productIssueB == false) { Assert.Fail("No information about error cause."); } // Checking if another one is not visible errorTextTemp = "Extra error"; bool uploadedFileIssue = tmethods.IsElementNotVisible(driver, By.XPath("//*[contains(.,'" + errorTextTemp + "')]")); if (uploadedFileIssue == false) // Should be set to true { Assert.Fail("Extra error shown."); } ``` I use two methods here: ``` public bool IsElementVisible(IWebDriver driver, By element) { if (driver.FindElements(element).Count > 0) { if (driver.FindElement(element).Displayed) return true; else return false; } else { return false; } } public bool IsElementNotVisible(IWebDriver driver, By element) { if (driver.FindElements(element).Count > 0) { if (driver.FindElement(element).Displayed) return false; else return false; } else { return true; } } ``` So, all of that is working, but I am not sure about quality of that code. On the other hand, I don't need anything over-fancy. It just should be good, clean and understandable. Should I keep it intact or update some parts?
- pattern minor 112d agoPress any login button on any siteI'm working on a script that will be able to press the login button on any site for an app I'm working on. I have it working (still a few edge cases to work out such as multiple submit buttons and iFrames and I'm going to rewrite it to make it prettier once I figure them out). Can you think of any ways I could improve it or make it more robust? Some notes: - `form.submit()` doesn't work consistently since many sites don't allow it to be executed via a script. - Three types of login buttons I see consistently are 'a', 'button', and 'input'. ``` var buttonElements = document.getElementsByTagName('button'); var inputElements = document.getElementsByTagName('input'); var linkElements = document.getElementsByTagName('a'); var loginElement = null; // For Button/Input if (buttonElements != null){ loginElement = getSubmitElement(buttonElements); } if (loginElement != null){ console.log(loginElement); loginElement.click(); } else{ if (inputElements != null){ loginElement = getSubmitElement(inputElements); } if (loginElement != null){ console.log(loginElement); loginElement.click(); } else{ if (linkElements != null){ loginElement = getLinkElement(linkElements); } if (loginElement != null){ console.log(loginElement); loginElement.click(); } } } // Used for link elements () function getLinkElement(elements){ for (i=0;i < elements.length; i++){ // Is a submit button // Check ID class if (isLoginElement(elements[i],'id')){ return elements[i]; } } for (i=0;i < elements.length; i++) { if(isLoginElement(elements[i], 'name')){ return elements[i]; } else if(isLoginElement(elements[i],'class')){ return elements[i]; } } return null; } // Use for Button or Input - Checks the id/name/class attributes function getSubmitElement(elements){
- pattern minor 112d agoMixing Watir::Browser into RSpecIn my previous Watir question I was making a module with `session_FF` accepting a block. Now I want to make the same but via RSpec. Here is my try: ``` require "rspec" require "watir" module Session_FF def method_missing m, *args, &block @browser.send m, *args, &block end def element *args elements = @browser.elements *args case elements.size when 1 ; elements.first when 0 ; raise "found no nodes using search args: #{args}" else ; raise "found #{es.size} nodes -- use #elements method or improve args" end end end RSpec.configure do |config| config.include Session_FF config.before{ @browser ||= Watir::Browser.new :ff} config.after{ @browser.quit } end describe "it" do it "is alive" do goto "http://example.com/" element(class: "userpanel").click end end ``` I see a problem, that previously I was defining `method_missing` in my own module but now `include` may redefine `RSpec::Core::ExampleGroup` or smth's `#method_missing` if it already exists or may appear in RSpec implementation. What is a better way for `method_missing` approach to forward browser interaction methods into `@browser`?
- pattern minor 112d agoOpening TV episodes in a web browserI put this together and it seems to work. 1channel.py -breakingbad 1 The Output (1-10): ``` (1) - Currently 3.80/5 (2) - Currently 3.50/5 ``` (1 opens the link in browser) If anyone has any suggestions or wants to improve it: ``` from bs4 import BeautifulSoup import urllib2, sys, webbrowser def Work(tvshow): print "\n[*] Working...\n" try: f = urllib2.urlopen(tvshow) html = f.read() soup = BeautifulSoup(html) for table in soup.findAll('table',{"width":"100%"}): for a in table.findAll('a',{"target":"_blank"}): for li in table.findAll('li',{"class":"current-rating"}): if a.text=="Version 2": print "(1) - %s\n" % (li.text) link1 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 3": print "(2) - %s\n" % (li.text) link2 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 4": print "(3) - %s\n" % (li.text) link3 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 5": print "(4) - %s\n" % (li.text) link4 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 6": print "(5) - %s\n" % (li.text) link5 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 7": print "(6) - %s\n" % (li.text) link6 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 8": print "(7) - %s\n" % (li.text) link7 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 9": print "(8) - %s\n" % (li.text) link8 = "http://www.1chan