CS计算机代考程序代写 Java python cache Excel database Rapid Application Development

Rapid Application Development
COSC2675 2021 Week 9
A/Prof. Andy Song andy.song@rmit.edu.au
In Week 8
• Many-to-many
• Join tables
• Many-to-many controllers
• Many-to-many views
• Nested resources
A/Prof. Andy Song RMIT University 2021
2

Debugging
• Rails can show what is wrong while applications are running, similar to the PRINT statement for debugging.
• Ifyouwanttodebug<%=@student%>,simplywrite <%= debug(@student) %>
• This method will show (not complete) — !ruby/ object:Student
raw_attributes:
given_name: Alex family_name: Bay id: 2
….
attributes: !ruby/ object:ActiveRecord:: AttributeSet attributes: !ruby/ object:ActiveRecord:: LazyAttributeHash
types:
id: &5 !ruby/ object
precision:

range: !ruby/ range
begin: -2147483648
end: 2147483648 excl: true new_record: false
active_record_yaml_version: 1 3 A/Prof. Andy Song RMIT University 2021
Raising Exceptions
• Youmayabuseexceptiontoshowvariablesinsideofa controller before data reach the view
# GET /awards/ 1
# GET /awards/ 1.json
def show
raise @award.to_yaml
end
• AYAMLdumpwillshowalltheinfointheawardvariable.
• YAML (Yet Another Markup Language􏰀 then YAML Ain’t Markup Language) is a data serialization language, commonly used for config files.
• YAMLisasupersetofJSON,nativelyencodescalars,lists and hashes.
— # Programming Courses
[Java, Perl, Rails, Python]
— # Student Data
{name: Alex Bay, age: 20} 4
A/Prof. Andy Song RMIT University 2021

Raising Exceptions
Don’t forget to remove raise after use, especially for the
production stage.
(Learning Rails 5, Mark Locklear Eric Gruber) 5 A/Prof. Andy Song RMIT University 2021
Logging
• Logging starts when you entered $ rails server
• Alllogsarestoredinthelog/development.logfile
• Therewillbetest.logandproduction.logifthe application runs in test or production mode.
• You can use logger object in model, controller or view
logger.info ‘This is a message to send to the log’ logger.error(“Line in wrong format: #{line.chomp}”) logger.fatal(“Caught exception; exiting”)
Logger shows timing information as well, e.g. how long the view rendering is, how long the DB took to act etc.
Completed in 0.01451 (68 reqs/ sec) | Rendering: 0.00775 (53%)
| DB: 0.00093 (6%) | 200 OK
A/Prof. Andy Song RMIT University 2021
6

Working with the Console
• rails console
An interactive Ruby Shell (irb) will start, which has the full
context of your application.
You may have console and server running at the same time in different windows.
• rails console –sandbox
With the sandbox option (-s) the database would not be
changed. Everything rolls back to original after the session. • All methods on the model are available in irb
> s = Student.find(1)
> s.name
> irb s //session in the context of s only
> name
> exit
> s.middle_name = ‘Kent’
A/Prof. Andy Song RMIT University 2021
7
Methods & Objects for Console
>ys
The y method (YAML) is to show the content of variable s
> s.save
>ys
> exit // sandbox mode
(0.6ms) rollback transaction
Two convenient objects: helper and app.
Helper gives access to all the helper methods in the application.
> helper.score_to_mark 78
=> “DI”
App gives you access to full application context, including routing table so you can test the routing.
> app.url_for :action=>”index”, :controller=>”courses”
=> “http://www.example.com/courses”
> app.url_for :action = >”new”, :controller=>”courses”
=> “http://www.example.com/courses/new” 8 A/Prof. Andy Song RMIT University 2021

App with URLs
> include Rails.application.routes.url_helpers > new_course_path
=> ”/courses/new”
> app.get ”/students/2″
Student Load (0.3ms)
SELECT “students”.* FROM “students” WHERE “students”.”id”
= ? LIMIT 1 [[” id”, “2”]]
(0.2ms) SELECT COUNT() FROM “courses” INNER JOIN
“courses_students” ON “courses”.”id”=”courses_students”. ”course_id” WHERE “courses_students”.”student_id”=2
Award Load (0.2ms)
SELECT “awards”.* FROM “awards” WHERE “awards”.” student_id” = 2 Student Load (0.2ms)
SELECT “students”.* FROM “students” WHERE “students”.” id” = 2 LIMIT 1
=> 200
This 200 simply says the request was success.
A/Prof. Andy Song RMIT University 2021
9
App with URLs/Reload!
> app.controller.params
= > “students”, “action”=>”show”, “id”=>”2”} permitted: false>
It clearly shows how the routing interprets the request and calls the controller.
> app.response.body
=> “\n\n\nStudents \n app.header
Displays the header information
> reload!
Reload the updated application code and use the code. (Objects which have been created already, need to be removed.)
A/Prof. Andy Song RMIT University 2021
10

Debugger
The console is a great way to trying things out, but not a part of Rails development process.
Adding debug statements can be helpful, but may not be enough. When you need to dig deep, then the debugger is the best option.
In app/controllers/students_controller.rb
def create
@student = Student.new(student_params)
debugger
respond_to do |format|
if @student.save
format.html { redirect_to @student, notice: Student
was successfully created. }
format.json { render:show, status: :created,
location: @student }
else
format.html { render :new} . . . . .
A/Prof. Andy Song RMIT University 2021
11
Debugger …
Visit http://localhost:3000/students/new, enter a new student, then click the create button. You will see
(Learning Rails 5, Mark Locklear Eric Gruber) 12 A/Prof. Andy Song RMIT University 2021

Debugger . . . . . .
The application stops and “Waiting for localhost…”
Go to the console you will see it is waiting at a byebug prompt.
(Learning Rails 5, Mark Locklear Eric Gruber)
If type next, the next statement right after debugger will be executed. If type list, lines of source code will be shown
A/Prof. Andy Song RMIT University 2021
13
Debugger commands
• next, (or step) to move forward to the next line.
• cont to leave the debugger and let the application continue. • quit to leave the debugger and shut down Rails
• p or pp to inspect variables.
(byebug) p @student
#, start_date:
“2016-11-16”, created_at: nil, updated_at: nil >
• irb to start an irb shell to inspect variables, e.g. y @student
• list- (or l-) to show the previous ten lines
• list= to see where you are in the code A/Prof. Andy Song RMIT University 2021
14

break catch condition continue debug delete disable display down edit enable finish frame help history info interrupt
— Sets breakpoints in the source code — Handles exception catchpoints
— Sets conditions on breakpoints
— Runs until program ends, hits a breakpoint or reaches a line — Spawns a subdebugger
— Deletes breakpoints
— Disables breakpoints or displays
— Evaluates expressions every time the debugger stops — Moves to a lower frame in the stack trace
— Edits source files
— Enables breakpoints or displays
— Runs the program until frame returns
— Moves to a frame in the call stack
— Helps you using byebug
— Shows byebug’s history of commands
— Shows several informations about the program being debugged
— Interrupts the program
A/Prof. Andy Song RMIT University 2021
15
Debugger help
kill
list method next
pry
quit restart save
set
show source step thread tracevar undisplay untracevar up
var
where
— Sends a signal to the current process — Lists lines of source code
— Shows methods of an object, class or module — Runs one or more lines of code
— Starts a Pry session
— Exits byebug
— Restarts the debugged program
— Saves current byebug session to a file
— Modifies byebug settings
— Shows byebug settings
— Restores a previously saved byebug session
— Steps into blocks or methods one or more times
— Commands to manipulate threads
— Enables tracing of a global variable
— Stops displaying all or some expressions when program stops
— Stops tracing a global variable
— Moves to a higher frame in the stack trace — Shows variables and its values
— Displays the backtrace
A/Prof. Andy Song RMIT University 2021
16
Debugger help

Gems for Debugging
• Byebug http://guides.rubyonrails.org/debugging_rails_applications.html
• Pry -anirbtypeofdebuggingtool
gem ‘pry-rails’, group: [:development, :test]
• binding.pry – set the breakpoint • Then use commands like:
− $
− show-routes − show-models
− whereami
show source
print the context
A/Prof. Andy Song RMIT University 2021
17
Three Modes of Rails
Rails supports three different environments:
Development Mode: the default mode.
– Rails loads and reloads code every time a request is made. – Easy to see changes.
– It’s also typical to use SQLite as the database
Test Mode: runs like production without reloading code – has its own database
– the default DB is SQLite
Production Mode: maximizes Rails efficiency
– does not reload, enables caching, runs much faster.
– Logging is much briefer, error messages are shortened
– more automatic and directed caching of results, so no need to
wait for the same code to run again.
18
A/Prof. Andy Song RMIT University 2021

Three Modes of Rails
File config/environment.rb is the default setting for three modes. config/environments/development.rb
config.cache_classes = false config.consider_all_requests_local = true
config/environments/production.rb
config.cache_classes = true config.consider_all_requests_local = false
config/environments/test.rb
config.cache_classes = true config.consider_all_requests_local = true
File database.yml is the database settings for all three modes. By default, it specifies SQLite databases named db/development.sqlite3,
db/test.sqlite3, and
db/production.sqlite3
$rails server –e test enters test mode A/Prof. Andy Song RMIT University 2021
19
config.eager_load = false
config.eager_load = true
config.eager_load = false
Tests
• For model tests
$ rails test:models
• For controller tests
$ rails test:controllers
• Foraspecifictestfile
$ rails test TEST=test/controller/courses_test.rb
Before running these tests, make sure you run
$ rails db:migrate
A/Prof. Andy Song RMIT University 2021
20

Test Data – Fixtures
• Rails provides a stable test environment − With its own separate database
− With stable data, called fixtures
• When a new test is running, the database is reset to that stable set of data
• This is slow, but is extremely reliable
• Fixtures are also written in YAML
• Placed under test/fixtures
A/Prof. Andy Song RMIT University 2021
21
Generated Fixture
test/fixtures/students.yml
# Read about fixtures at
# http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
one:
given_name: MyString
middle_name: MyString
family_name: MyString
date_of_birth: 2021-05-01
grade_point_average: 9.99
start_date: 2021-05-01
two:
given_name: MyString
middle_name: MyString
family_name: MyString
date_of_birth: 2021-05-01
grade_point_average: 9.99
start_date: 2021-05-01
Generated fixtures can be null and lead to many mysterious errors.
Fixtures can be generated , but better to be defined manually.
22
A/Prof. Andy Song RMIT University 2021

Adding data in the fixture
test/fixtures/students.yml
#test/fixtures/students.yml
magnum:
given_name: Thomas
middle_name: Sullivan
family_name: Magnum
date_of_birth: 2002-01-29
grade_point_average: 2.92
start_date: 2019-07-15
rick:
given_name: Orville
middle_name: Wilbur
family_name: Richard
date_of_birth: 2003-07-23
grade_point_average: 3.94
start_date: 2020-03-02
Adding meaningful data can be useful, especially in finding failures.
A/Prof. Andy Song RMIT University 2021
23
Model Testing
test/models/award_test.rb
require ‘test_helper’
class AwardTest < ActiveSupport:: TestCase # test "the truth" do # assert true # end end The Rails-generated test uses the assert statement, which expects the return value of true. Otherwise it will report a failure. Tests are pretty straightforward to write. They should reflect the validations performed by the model. For the award example, we can test for the presence of names, years and the year being 1980 or later. (app/models/award.rb) validates_presence_of :name, :year validates_inclusion_of :year, in: (1980..Date.today.year) 24 A/Prof. Andy Song RMIT University 2021 Test Award test/models/award_test.rb require 'test_helper' class AwardTest < ActiveSupport:: TestCase def test_validity_of_year # create new student for association in award student = Student.create({given_name: "Mark", date_of_birth: "2002-09-05", start_date: "2019-02-18"}) # test for rejection of missing year award=Award.new({name:"Test award”,student_id: student.id}) assert !award.valid? # test under lower boundary award.year = 1979 assert !award.valid? # lower boundary award.year = 1980 assert award.valid? # top boundary award.year = Date.today.year assert award.valid? # top boundary case, award isn't valid for next year award.year = Date.today.year + 1 assert !award.valid? end 25 end A/Prof. Andy Song RMIT University 2021 Test Award . . . After adding the test code, run the test, we should see: $ rails test:models Run options: --seed 52905 # Running: ... Finished in 0.054994s,18.1837 runs/s,90.9183 assertions/s 1 runs, 5 assertions, 0 failures, 0 errors, 0 skips The valid? method is called. It checks an object with a set of values against the validations defined in the model. Each assertion pushes against a rule about the year’s value. Some purists prefer to have only one assertion per test. That is often found in traditional unit testing. 26 A/Prof. Andy Song RMIT University 2021 Test Student (Learning Rails 5, Mark Locklear Eric Gruber) 27 A/Prof. Andy Song RMIT University 2021 Test Student . . . The first line specifies the fixtures to be loaded for the test. fixture :students, :courses The test_validity method is to test the student Jonathan. The test_name method is to test the name concatenation. The assert methods here have an extra argument, the message. The test_enrolled_in relies on the fixture which says tc is enrolled in aviation but not in security. The test_unenrolled_courses also relies on the fixture which says magnum and rick are not enrolled in aviation but all other courses. $ rails test:models should have 0 failures, 0 errors, 0 skips. A/Prof. Andy Song RMIT University 2021 28 Tests are valuable Model tests accumulate over time. They serve as a warning that something has changed (by other team members) Tests can be created first and set as the goal of the application. This is known as TDD – Test Driven Development – excellent practice, widely used in industry. Once a test is written, it will run every time when Rails is testing the application. You don’t need to go back and check things are still working. Tests can become part of a continuous integration environment where tests are automatically performed on code repository. A/Prof. Andy Song RMIT University 2021 29 Controller Testing Tests generated for models do nothing, but tests generated for controllers have a basic structure. They are in test/controllers directory. Tests created by the REST scaffolding are particularly useful. Controllers are called via the GET/PUT/POST/DELETE methods. Controller testing does not create HTTP request but go to the controller directly. (Learning Rails 5, Mark Locklear Eric Gruber) 30 A/Prof. Andy Song RMIT University 2021 Controller Testing... Some minor changes to modify from the left to the right. (Learning Rails 5, Mark Locklear Eric Gruber) g RMIT University 2017 31 Dr. Andy Son Assertion Methods assert_not_nil to test that a given variable is not nil. assert_response to compare the HTTP response that the controller sends to the argument. :success for200 :redirect for 300-399 :missing for404 :error for 500-599 assert_redirected_to to check the location redirected by the controller assert_difference to compare a method return with an integer. An added record would just be +1, A deleted record would be -1 assert_no_difference the opposite A/Prof. Andy Song RMIT University 2021 32 Integration Testing Integration testing is Rails’ most complicated testing. It tests complete incoming requests, routing, controllers, models, the database and even views. Integration tests are stored in test/integration To generate the integration test $rails g integration_test student The generated tests are not much. So you need to create the tests. To run the integration test: $rails test:integration A/Prof. Andy Song RMIT University 2021 33 Assertion for Views assert_select to test HTML documents. Other view testing assertion methods: assert_tag assert_no_tag assert_dom_equal assert_dom_not_equal assert_select_encoded assert_select_rjs A/Prof. Andy Song RMIT University 2021 34 Summary • Debugging • Logging • Working with the console • Debugger • Rails three modes • Fixtures • Model testing • Controller testing • Assertion methods • Integration testing A/Prof. Andy Song RMIT University 2021 35