not handling the file upload window well - watir

I have a page object called import_transaction_file.rb, which one of the method click_choose_file will invoke a standard file upload windows show below:
the code for the page object is:
class ImportTransactionFile
include PageObject
....
button(:choose_file, :id => 'createBulkPayment:file')
....
def click_choose_file
choose_file
end
end
In my test program below:
....
def test_go_to_direct_credit_payment_page
...
#import_transaction.click_choose_file
# #browser.window(:title => 'File Upload').use do
# #browser.button(:name => 'Cancel').click
# end
# doesn't work
end
the method click_choose_file in the test program will invoke the standard file upload window as attached below:
How do I:
put the path to file name
click open button
click close button
Will you recommend me to do it in the page-object or the test program?
Thanks for your reply.

I have a very similar thing to what you're asking and mine works using:
browser.file_field(:text, "File Upload").set("C:\path\to\file\to\upload")
Hope that helps!

Related

Flask file download: filename persists within the session

I have a flask site and a webform that generates excel files. The problem I'm having is, if I send the user back to the form to submit again, the previous file -- with same file name and data -- is downloaded even though new files are generated in the tmp directory. So, I think this has to do with my session variable.
I add a timestamp to the file name with this function to make sure the file names are unique:
def rightnow():
return dt.datetime.now().strftime("%m%d%y%h%m%S%f")
In routes.py, here is the call for the download:
#app.route('/download/', methods=['POST','GET'])
def download_file():
output_file = session.get('new_file', None)
r = send_file(output_file, attachment_filename=output_file, as_attachment=True)
return r
This is the code for the script that generates the excel files:
new_file = 'output_' + rightnow() + '.xlsx'
writer = pd.ExcelWriter('tmp/' + new_file, engine='xlsxwriter')
df.to_excel(writer, sheet_name="data")
writer.save()
session['new_file'] = 'tmp/' + new_file
The download statement from the template page:
<a class="button" href="{{url_for('download_file')}}">Download new data</a>
I have a "Submit Again" button tied to simple javascript
<button onclick="goBack()">Submit Again</button>
<script>//for "revise search" button
function goBack() {
window.history.back();
}
</script>
I have played around with session.clear() with no success.
How can I drop the session when the user click's the "Submit Again" button so the saved file name is dropped?
EDIT: I checked the variables for the filename and the session variable and they are identical, and different from the file name assigned on download. Forinstance, the file is named 'output_May0554733504.xlsx' by the script that I wrote -- I can see it in the tmp directory. But when I go to download the file, the filename is different: 'output_May0536794357.xlsx'
This other file name is not that of a different file in the tmp directory. Any file I download will be 'output_May0536794357.xlsx'.
If session.pop('new_file') doesn't work, you could try session.modified = True to force the change to the session.

How to automatically handle DialogBoxShowing event in Python(Revit Dynamo)?

How do I subscribe to Revit events in Python (Dynamo)?
Specifically DialogBoxShowing so I can see if it is "Export with Temporary Hide/Isolate" warning and select "Leave the Temporary Isolate Mode on and Export"?
It is done in C# here:
http://thebuildingcoder.typepad.com/blog/2013/03/export-wall-parts-individually-to-dxf.html
See sub-heading: Handling and Dismissing a Warning Message
Thanks!
To make it more simple than in the tutorial :
Inside Revit, with RevitPythonShell, the event subscribing part can be very easy.
An event handler is just a callable with two arguments : senderand event. Then the event, or the sender gives parameters to play with, DialogId and OverrideResultin our case.
To keep the Building Coder example, let's go with :
def on_dialog_open(sender, event):
try:
if event.DialogId == 'TaskDialog_Really_Print_Or_Export_Temp_View_Modes':
event.OverrideResult(1002)
# 1001 call TaskDialogResult.CommandLink1
# 1002 call TaskDialogResult.CommandLink2
# int(TaskDialogResult.CommandLink2) to check the result
except Exception as e:
pass #print(e) # uncomment this to debug
You only need to plug this function to an event with the following syntax :
__uiControlledApplication__.DialogBoxShowing += on_dialog_open
This can be done in the startup file of RevitPythonShell :
C:\Users\USERNAME\AppData\Roaming\RevitPythonShell2017\startup.py
(Or in the startup part of your addin)
The better way is to unregister the handler if you don't need it anymore, i.e. when Revit is closing (check the tutorial for more details) :
__uiControlledApplication__.DialogBoxShowing -= on_dialog_open
If you want to try this within the console, you can use :
def on_dialog_open(sender, event):
# [...]
__revit__.DialogBoxShowing += on_dialog_open
And after you try an export:
__revit__.DialogBoxShowing -= on_dialog_open
EDIT : shortcuts for result commands (thanks Callum !)
('Cancel', 2)
('Close', 8)
('CommandLink1', 1001)
('CommandLink2', 1002)
('CommandLink3', 1003)
('CommandLink4', 1004)
('No', 7)
('None', 0)
('Ok', 1)
('Retry', 4)
('Yes', 6)
To answer your first question. Try to read this tutorial from Pierre Moureu : https://github.com/PMoureu/samples-Python-RPS/tree/master/Tutorial-IUpdater.
He his subscribing to a IUpdater.
(sorry not enough reputation to add this as comment to the response by PRMoureu...)
To expand on handling Dialogs a little...
Subscribing to DialogBoxShowing is hugely powerful, we have just rolled out a Dialog Suppressor to silence the ever-frustrating 'Would you like to join walls to the floor you just made' and 'Would you like to attach these walls to the roof'. It can also be used to see what errors users are commonly getting etc.
To investigate a Dialogs message text: event.Message
To reply 'Cancel' to the Dialog: event.OverrideResult(0)
To reply 'Yes' to the Dialog: event.OverrideResult(1)
To reply 'OK' to the Dialog: event.OverrideResult(6)

How to save a table to a file from Lua

I'm having trouble printing a table to a file with lua (and I'm new to lua).
Here's some code I found here to print the table;
function print_r ( t )
local print_r_cache={}
local function sub_print_r(t,indent)
if (print_r_cache[tostring(t)]) then
print(indent.."*"..tostring(t))
else
print_r_cache[tostring(t)]=true
if (type(t)=="table") then
for pos,val in pairs(t) do
if (type(val)=="table") then
print(indent.."["..pos.."] => "..tostring(t).." {")
sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
print(indent..string.rep(" ",string.len(pos)+6).."}")
elseif (type(val)=="string") then
print(indent.."["..pos..'] => "'..val..'"')
else
print(indent.."["..pos.."] => "..tostring(val))
end
end
else
print(indent..tostring(t))
end
end
end
if (type(t)=="table") then
print(tostring(t).." {")
sub_print_r(t," ")
print("}")
else
sub_print_r(t," ")
end
print()
end
I have no idea where the 'print' command goes to, I'm running this lua code from within another program. What I would like to do is save the table to a .txt file. Here's what I've tried;
function savetxt ( t )
local file = assert(io.open("C:\temp\test.txt", "w"))
file:write(t)
file:close()
end
Then in the print-r function I've changed everywhere it says 'print' to 'savetxt'. This doesn't work. It doesn't seem to access the text file in any way. Can anyone suggest an alternative method?
I have a suspicion that this line is the problem;
local file = assert(io.open("C:\temp\test.txt", "w"))
Update;
I have tried the edit suggested by Diego Pino but still no success. I run this lua script from another program (for which I don't have the source), so I'm not sure where the default directory of the output file might be (is there a method to get this programatically?). Is is possible that since this is called from another program there's something blocking the output?
Update #2;
It seems like the problem is with this line:
local file = assert(io.open("C:\test\test2.txt", "w"))
I've tried changing it "C:\temp\test2.text", but that didn't work. I'm pretty confident it's an error at this point. If I comment out any line after this (but leave this line in) then it still fails, if I comment out this line (and any following 'file' lines) then the code runs. What could be causing this error?
I have no idea where the 'print' command goes to,
print() output goes to default output file, you can change that with io.output([file]), see Lua manuals for details on querying and changing default output.
where do files get created if I don't specify the directory
Typically it will land in current working directory.
Your print_r function prints out a table to stdout. What you want is to print out the output of print_r to a file. Change the print_r function so instead of printing to stdout, it prints out to a file descriptor. Perhaps the easiest way to do that is to pass a file descriptor to print_r and overwrite the print function:
function print_r (t, fd)
fd = fd or io.stdout
local function print(str)
str = str or ""
fd:write(str.."\n")
end
...
end
The rest of the print_r doesn't need any change.
Later in savetxt call print_r to print the table to a file.
function savetxt (t)
local file = assert(io.open("C:\temp\test.txt", "w"))
print_r(t, file)
file:close()
end
require("json")
result = {
["ip"]="192.168.0.177",
["date"]="2018-1-21",
}
local test = assert(io.open("/tmp/abc.txt", "w"))
result = json.encode(result)
test:write(result)
test:close()
local test = io.open("/tmp/abc.txt", "r")
local readjson= test:read("*a")
local table =json.decode(readjson)
test:close()
print("ip: " .. table["ip"])
2.Another way:
http://lua-users.org/wiki/SaveTableToFile
Save Table to File
function table.save( tbl,filename )
Load Table from File
function table.load( sfile )

Download xls file from application rails 4

I am using rails 4 application, where i have a xls file in my applications public folder ,and am having a link in view page after clicking that link that xls file should download to system.no need to write anything in that file its just a default template.
I use:
view:
<%= link_to "Dowload Template", admin_job_templates_path, :file_name => 'Job_Upload_Template.xlsx' %>
controller :
def index
require 'open-uri'
file_path = "#{Rails.root}/public/Job_Upload_Template.xlsx"
send_file file_path, :filename => "Job_Upload_Template.xlsx", :disposition => 'attachment'
end
also tried send_data method
def index
require 'open-uri'
url = "#{Rails.root}/public/Job_Upload_Template.xlsx"
data = open(url).read
send_data data, :filename =>'Job Template'
end
Am getting the below error.
No such file or directory # rb_sysopen -
/home/amp/workspace/LA_Tracker/public/Job_Upload_Template.xlsx
am not able to dowload the file, Plese help.
It's telling you that file doesn't exist. Do you have the capitalization correct? Double check. Also, what happens if you type:
ls /home/amp/workspace/LA_Tracker/public/Job_Upload_Template.xlsx
into the command line? Can your OS find the file?

page-object gem seems not working

I am trying to use page-object gem in my watir-webdriver scripts and I think I might be missing something.
Here is my code for log_in.rb:
require "./all_deals"
class LogIn
include PageObject
text_field(:email, :id => 'UserName')
text_field(:password, :id => 'Password')
checkbox(:remember_me, :id => 'RememberMe')
button(:log_me_in, :value => 'Login')
def initialize(browser)
#browser = browser
end
def log_in (email, password)
self.email = email
self.password = password
remember_me
log_me_in
AllDeals.new(#browser)
end
end
My home_page.rb
require "./log_in"
class HomePage
def initialize(browser)
#browser = browser
end
def visit
#browser.goto "http://treatme.co.nz/"
end
def go_to_log_in
#browser.goto "https://treatme.co.nz/Account/LogOn"
LogIn.new(#browser)
end
end
Here is my log_in_test.rb
require "rubygems"
require "test/unit"
require "watir-webdriver"
require "page-object"
require "./home_page"
class LogInTest < Test::Unit::TestCase
def setup
#browser ||= Watir::Browser.new :firefox
end
def teardown
#browser.close
end
def test_fail
#home_page = HomePage.new(#browser)
#home_page.visit
#log_in_page = #home_page.go_to_log_in
#all_deals = #log_in_page.log_in("test#gmail.com","test")
assert (#all_deals.get_title == "GrabOne Daily Deals - Buy Together, Save Together")
end
end
The result of the test run is:
Finished tests in 22.469286s, 0.0445 tests/s, 0.0000 assertions/s.
1) Error:
test_fail(LogInTest):
NoMethodError: undefined method `text_field_value_set' for nil:NilClass
C:/Ruby193/lib/ruby/gems/1.9.1/gems/page-object-0.9.2/lib/page-object/accessors.rb:142:in `block in text_field'
I am using Ruby 1.9 with page-object gem 0.9.2.
Can you please help me?
Also in each of those rb file, I need to require the class files it references, is there a way I don't have to declare it every time?
Thanks so much.
Addressing the Exception
That exception is occurring do to the LogIn page re-defining the initialize method.
class LogIn
include PageObject
def initialize(browser)
#browser = browser
end
end
When you include PageObject, it already adds a specific initialization method. Your class is overriding that initialization and presumably causing something to not get setup correctly.
Removing the initialize method will get you past that exception.
However, you will then hit a remember_me is not a variable/method exception. Assuming you want to check the checkbox, it should be check_remember_me.
Requiring Class Files
I usually have my test file require a file that requires all my page_objects. It is a similar concept to how your would require any other gem or library.
For example, I would create a treatme.rb file with:
require 'log_in'
require 'home_page'
Assuming you require the files in the required order (ie files that are needed by others are required first), none of your page object files (ie log_in.rb and home_page.rb) should need to do any requiring.
Your test files would then just require your treatme.rb file. Example:
require './treatme'

Resources