Warning: file_get_contents(https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/ru.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 88

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 215

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 216

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 217

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 218

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 219

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 220
PK!2Vii collector.rbnu[module Test module Unit module Collector def initialize @filters = [] end def filter=(filters) @filters = case(filters) when Proc [filters] when Array filters end end def add_suite(destination, suite) to_delete = suite.tests.find_all{|t| !include?(t)} to_delete.each{|t| suite.delete(t)} destination << suite unless(suite.size == 0) end def include?(test) return true if(@filters.empty?) @filters.each do |filter| result = filter[test] if(result.nil?) next elsif(!result) return false else return true end end true end def sort(suites) suites.sort_by{|s| s.name} end end end end PK!x testcase.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved. # License:: Ruby license. require 'test/unit/assertions' require 'test/unit/failure' require 'test/unit/error' require 'test/unit/testsuite' require 'test/unit/assertionfailederror' require 'test/unit/util/backtracefilter' module Test module Unit # Ties everything together. If you subclass and add your own # test methods, it takes care of making them into tests and # wrapping those tests into a suite. It also does the # nitty-gritty of actually running an individual test and # collecting its results into a Test::Unit::TestResult object. class TestCase include Assertions include Util::BacktraceFilter attr_reader :method_name STARTED = name + "::STARTED" FINISHED = name + "::FINISHED" ## # These exceptions are not caught by #run. PASSTHROUGH_EXCEPTIONS = [NoMemoryError, SignalException, Interrupt, SystemExit] # Creates a new instance of the fixture for running the # test represented by test_method_name. def initialize(test_method_name) unless(respond_to?(test_method_name) and (method(test_method_name).arity == 0 || method(test_method_name).arity == -1)) throw :invalid_test end @method_name = test_method_name @test_passed = true end # Rolls up all of the test* methods in the fixture into # one suite, creating a new instance of the fixture for # each method. def self.suite method_names = public_instance_methods(true) tests = method_names.delete_if {|method_name| method_name !~ /^test./} suite = TestSuite.new(name) tests.sort.each do |test| catch(:invalid_test) do suite << new(test) end end if (suite.empty?) catch(:invalid_test) do suite << new("default_test") end end return suite end # Runs the individual test method represented by this # instance of the fixture, collecting statistics, failures # and errors in result. def run(result) yield(STARTED, name) @_result = result begin setup __send__(@method_name) rescue AssertionFailedError => e add_failure(e.message, e.backtrace) rescue Exception raise if PASSTHROUGH_EXCEPTIONS.include? $!.class add_error($!) ensure begin teardown rescue AssertionFailedError => e add_failure(e.message, e.backtrace) rescue Exception raise if PASSTHROUGH_EXCEPTIONS.include? $!.class add_error($!) end end result.add_run yield(FINISHED, name) end # Called before every test method runs. Can be used # to set up fixture information. def setup end # Called after every test method runs. Can be used to tear # down fixture information. def teardown end def default_test flunk("No tests were specified") end # Returns whether this individual test passed or # not. Primarily for use in teardown so that artifacts # can be left behind if the test fails. def passed? return @test_passed end private :passed? def size 1 end def add_assertion @_result.add_assertion end private :add_assertion def add_failure(message, all_locations=caller()) @test_passed = false @_result.add_failure(Failure.new(name, filter_backtrace(all_locations), message)) end private :add_failure def add_error(exception) @test_passed = false @_result.add_error(Error.new(name, exception)) end private :add_error # Returns a human-readable name for the specific test that # this instance of TestCase represents. def name "#{@method_name}(#{self.class.name})" end # Overridden to return #name. def to_s name end # It's handy to be able to compare TestCase instances. def ==(other) return false unless(other.kind_of?(self.class)) return false unless(@method_name == other.method_name) self.class == other.class end end end end PK!Fӥ testsuite.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved. # License:: Ruby license. module Test module Unit # A collection of tests which can be #run. # # Note: It is easy to confuse a TestSuite instance with # something that has a static suite method; I know because _I_ # have trouble keeping them straight. Think of something that # has a suite method as simply providing a way to get a # meaningful TestSuite instance. class TestSuite attr_reader :name, :tests STARTED = name + "::STARTED" FINISHED = name + "::FINISHED" # Creates a new TestSuite with the given name. def initialize(name="Unnamed TestSuite") @name = name @tests = [] end # Runs the tests and/or suites contained in this # TestSuite. def run(result, &progress_block) yield(STARTED, name) @tests.each do |test| test.run(result, &progress_block) end yield(FINISHED, name) end # Adds the test to the suite. def <<(test) @tests << test self end def delete(test) @tests.delete(test) end # Retuns the rolled up number of tests in this suite; # i.e. if the suite contains other suites, it counts the # tests within those suites, not the suites themselves. def size total_size = 0 @tests.each { |test| total_size += test.size } total_size end def empty? tests.empty? end # Overridden to return the name given the suite at # creation. def to_s @name end # It's handy to be able to compare TestSuite instances. def ==(other) return false unless(other.kind_of?(self.class)) return false unless(@name == other.name) @tests == other.tests end end end end PK!error.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # License:: Ruby license. require 'test/unit/util/backtracefilter' module Test module Unit # Encapsulates an error in a test. Created by # Test::Unit::TestCase when it rescues an exception thrown # during the processing of a test. class Error include Util::BacktraceFilter attr_reader(:test_name, :exception) SINGLE_CHARACTER = 'E' # Creates a new Error with the given test_name and # exception. def initialize(test_name, exception) @test_name = test_name @exception = exception end # Returns a single character representation of an error. def single_character_display SINGLE_CHARACTER end # Returns the message associated with the error. def message "#{@exception.class.name}: #{@exception.message}" end # Returns a brief version of the error description. def short_display "#@test_name: #{message.split("\n")[0]}" end # Returns a verbose version of the error description. def long_display backtrace = filter_backtrace(@exception.backtrace).join("\n ") "Error:\n#@test_name:\n#{message}\n #{backtrace}" end # Overridden to return long_display. def to_s long_display end end end end PK!o/ui/console/testrunner.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved. # License:: Ruby license. require 'test/unit/ui/testrunnermediator' require 'test/unit/ui/testrunnerutilities' module Test module Unit module UI module Console # Runs a Test::Unit::TestSuite on the console. class TestRunner extend TestRunnerUtilities # Creates a new TestRunner for running the passed # suite. If quiet_mode is true, the output while # running is limited to progress dots, errors and # failures, and the final result. io specifies # where runner output should go to; defaults to # STDOUT. def initialize(suite, output_level=NORMAL, io=STDOUT) if (suite.respond_to?(:suite)) @suite = suite.suite else @suite = suite end @output_level = output_level @io = io @already_outputted = false @faults = [] end # Begins the test run. def start setup_mediator attach_to_mediator return start_mediator end private def setup_mediator @mediator = create_mediator(@suite) suite_name = @suite.to_s if ( @suite.kind_of?(Module) ) suite_name = @suite.name end output("Loaded suite #{suite_name}") end def create_mediator(suite) return TestRunnerMediator.new(suite) end def attach_to_mediator @mediator.add_listener(TestResult::FAULT, &method(:add_fault)) @mediator.add_listener(TestRunnerMediator::STARTED, &method(:started)) @mediator.add_listener(TestRunnerMediator::FINISHED, &method(:finished)) @mediator.add_listener(TestCase::STARTED, &method(:test_started)) @mediator.add_listener(TestCase::FINISHED, &method(:test_finished)) end def start_mediator return @mediator.run_suite end def add_fault(fault) @faults << fault output_single(fault.single_character_display, PROGRESS_ONLY) @already_outputted = true end def started(result) @result = result output("Started") end def finished(elapsed_time) nl output("Finished in #{elapsed_time} seconds.") @faults.each_with_index do |fault, index| nl output("%3d) %s" % [index + 1, fault.long_display]) end nl output(@result) end def test_started(name) output_single(name + ": ", VERBOSE) end def test_finished(name) output_single(".", PROGRESS_ONLY) unless (@already_outputted) nl(VERBOSE) @already_outputted = false end def nl(level=NORMAL) output("", level) end def output(something, level=NORMAL) @io.puts(something) if (output?(level)) @io.flush end def output_single(something, level=NORMAL) @io.write(something) if (output?(level)) @io.flush end def output?(level) level <= @output_level end end end end end end if __FILE__ == $0 Test::Unit::UI::Console::TestRunner.start_command_line_test end PK!9977ui/gtk/testrunner.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # License:: Ruby license. require 'gtk' require 'test/unit/ui/testrunnermediator' require 'test/unit/ui/testrunnerutilities' module Test module Unit module UI module GTK # Runs a Test::Unit::TestSuite in a Gtk UI. Obviously, # this one requires you to have Gtk # (http://www.gtk.org/) and the Ruby Gtk extension # (http://ruby-gnome.sourceforge.net/) installed. class TestRunner extend TestRunnerUtilities # Creates a new TestRunner for running the passed # suite. def initialize(suite, output_level = NORMAL) if (suite.respond_to?(:suite)) @suite = suite.suite else @suite = suite end @result = nil @runner = Thread.current @restart_signal = Class.new(Exception) @viewer = Thread.start do @runner.join rescue @runner.run Gtk.main end @viewer.join rescue nil # wait deadlock to handshake end # Begins the test run. def start setup_mediator setup_ui attach_to_mediator start_ui @result end private def setup_mediator @mediator = TestRunnerMediator.new(@suite) suite_name = @suite.to_s if ( @suite.kind_of?(Module) ) suite_name = @suite.name end suite_name_entry.set_text(suite_name) end def attach_to_mediator run_button.signal_connect("clicked", nil, &method(:run_test)) @mediator.add_listener(TestRunnerMediator::RESET, &method(:reset_ui)) @mediator.add_listener(TestResult::FAULT, &method(:add_fault)) @mediator.add_listener(TestResult::CHANGED, &method(:result_changed)) @mediator.add_listener(TestRunnerMediator::STARTED, &method(:started)) @mediator.add_listener(TestCase::STARTED, &method(:test_started)) @mediator.add_listener(TestCase::FINISHED, &method(:test_finished)) @mediator.add_listener(TestRunnerMediator::FINISHED, &method(:finished)) end def run_test(*) @runner.raise(@restart_signal) end def start_ui @viewer.run running = false begin loop do if (running ^= true) run_button.child.text = "Stop" @mediator.run_suite else run_button.child.text = "Run" @viewer.join break end end rescue @restart_signal retry rescue end end def stop(*) Gtk.main_quit end def reset_ui(count) test_progress_bar.set_style(green_style) test_progress_bar.configure(0, 0, count) @red = false run_count_label.set_text("0") assertion_count_label.set_text("0") failure_count_label.set_text("0") error_count_label.set_text("0") fault_list.remove_items(fault_list.children) end def add_fault(fault) if ( ! @red ) test_progress_bar.set_style(red_style) @red = true end item = FaultListItem.new(fault) item.show fault_list.append_items([item]) end def show_fault(fault) raw_show_fault(fault.long_display) end def raw_show_fault(string) fault_detail_label.set_text(string) outer_detail_sub_panel.queue_resize end def clear_fault raw_show_fault("") end def result_changed(result) run_count_label.set_text(result.run_count.to_s) assertion_count_label.set_text(result.assertion_count.to_s) failure_count_label.set_text(result.failure_count.to_s) error_count_label.set_text(result.error_count.to_s) end def started(result) @result = result output_status("Started...") end def test_started(test_name) output_status("Running #{test_name}...") end def test_finished(test_name) test_progress_bar.set_value(test_progress_bar.get_value + 1) end def finished(elapsed_time) output_status("Finished in #{elapsed_time} seconds") end def output_status(string) status_entry.set_text(string) end def setup_ui main_window.signal_connect("destroy", nil, &method(:stop)) main_window.show_all fault_list.signal_connect("select-child", nil) { | list, item, data | show_fault(item.fault) } fault_list.signal_connect("unselect-child", nil) { clear_fault } @red = false end def main_window lazy_initialize(:main_window) { @main_window = Gtk::Window.new(Gtk::WINDOW_TOPLEVEL) @main_window.set_title("Test::Unit TestRunner") @main_window.set_usize(800, 600) @main_window.set_uposition(20, 20) @main_window.set_policy(true, true, false) @main_window.add(main_panel) } end def main_panel lazy_initialize(:main_panel) { @main_panel = Gtk::VBox.new(false, 0) @main_panel.pack_start(suite_panel, false, false, 0) @main_panel.pack_start(progress_panel, false, false, 0) @main_panel.pack_start(info_panel, false, false, 0) @main_panel.pack_start(list_panel, false, false, 0) @main_panel.pack_start(detail_panel, true, true, 0) @main_panel.pack_start(status_panel, false, false, 0) } end def suite_panel lazy_initialize(:suite_panel) { @suite_panel = Gtk::HBox.new(false, 10) @suite_panel.border_width(10) @suite_panel.pack_start(Gtk::Label.new("Suite:"), false, false, 0) @suite_panel.pack_start(suite_name_entry, true, true, 0) @suite_panel.pack_start(run_button, false, false, 0) } end def suite_name_entry lazy_initialize(:suite_name_entry) { @suite_name_entry = Gtk::Entry.new @suite_name_entry.set_editable(false) } end def run_button lazy_initialize(:run_button) { @run_button = Gtk::Button.new("Run") } end def progress_panel lazy_initialize(:progress_panel) { @progress_panel = Gtk::HBox.new(false, 10) @progress_panel.border_width(10) @progress_panel.pack_start(test_progress_bar, true, true, 0) } end def test_progress_bar lazy_initialize(:test_progress_bar) { @test_progress_bar = EnhancedProgressBar.new @test_progress_bar.set_usize(@test_progress_bar.allocation.width, info_panel.size_request.height) @test_progress_bar.set_style(green_style) } end def green_style lazy_initialize(:green_style) { @green_style = Gtk::Style.new @green_style.set_bg(Gtk::STATE_PRELIGHT, 0x0000, 0xFFFF, 0x0000) } end def red_style lazy_initialize(:red_style) { @red_style = Gtk::Style.new @red_style.set_bg(Gtk::STATE_PRELIGHT, 0xFFFF, 0x0000, 0x0000) } end def info_panel lazy_initialize(:info_panel) { @info_panel = Gtk::HBox.new(false, 0) @info_panel.border_width(10) @info_panel.pack_start(Gtk::Label.new("Runs:"), false, false, 0) @info_panel.pack_start(run_count_label, true, false, 0) @info_panel.pack_start(Gtk::Label.new("Assertions:"), false, false, 0) @info_panel.pack_start(assertion_count_label, true, false, 0) @info_panel.pack_start(Gtk::Label.new("Failures:"), false, false, 0) @info_panel.pack_start(failure_count_label, true, false, 0) @info_panel.pack_start(Gtk::Label.new("Errors:"), false, false, 0) @info_panel.pack_start(error_count_label, true, false, 0) } end def run_count_label lazy_initialize(:run_count_label) { @run_count_label = Gtk::Label.new("0") @run_count_label.set_justify(Gtk::JUSTIFY_LEFT) } end def assertion_count_label lazy_initialize(:assertion_count_label) { @assertion_count_label = Gtk::Label.new("0") @assertion_count_label.set_justify(Gtk::JUSTIFY_LEFT) } end def failure_count_label lazy_initialize(:failure_count_label) { @failure_count_label = Gtk::Label.new("0") @failure_count_label.set_justify(Gtk::JUSTIFY_LEFT) } end def error_count_label lazy_initialize(:error_count_label) { @error_count_label = Gtk::Label.new("0") @error_count_label.set_justify(Gtk::JUSTIFY_LEFT) } end def list_panel lazy_initialize(:list_panel) { @list_panel = Gtk::HBox.new @list_panel.border_width(10) @list_panel.pack_start(list_scrolled_window, true, true, 0) } end def list_scrolled_window lazy_initialize(:list_scrolled_window) { @list_scrolled_window = Gtk::ScrolledWindow.new @list_scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC) @list_scrolled_window.set_usize(@list_scrolled_window.allocation.width, 150) @list_scrolled_window.add_with_viewport(fault_list) } end def fault_list lazy_initialize(:fault_list) { @fault_list = Gtk::List.new } end def detail_panel lazy_initialize(:detail_panel) { @detail_panel = Gtk::HBox.new @detail_panel.border_width(10) @detail_panel.pack_start(detail_scrolled_window, true, true, 0) } end def detail_scrolled_window lazy_initialize(:detail_scrolled_window) { @detail_scrolled_window = Gtk::ScrolledWindow.new @detail_scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC) @detail_scrolled_window.set_usize(400, @detail_scrolled_window.allocation.height) @detail_scrolled_window.add_with_viewport(outer_detail_sub_panel) } end def outer_detail_sub_panel lazy_initialize(:outer_detail_sub_panel) { @outer_detail_sub_panel = Gtk::VBox.new @outer_detail_sub_panel.pack_start(inner_detail_sub_panel, false, false, 0) } end def inner_detail_sub_panel lazy_initialize(:inner_detail_sub_panel) { @inner_detail_sub_panel = Gtk::HBox.new @inner_detail_sub_panel.pack_start(fault_detail_label, false, false, 0) } end def fault_detail_label lazy_initialize(:fault_detail_label) { @fault_detail_label = EnhancedLabel.new("") style = Gtk::Style.new font = Gdk::Font.font_load("-*-Courier New-medium-r-normal--*-120-*-*-*-*-*-*") begin style.set_font(font) rescue ArgumentError; end @fault_detail_label.set_style(style) @fault_detail_label.set_justify(Gtk::JUSTIFY_LEFT) @fault_detail_label.set_line_wrap(false) } end def status_panel lazy_initialize(:status_panel) { @status_panel = Gtk::HBox.new @status_panel.border_width(10) @status_panel.pack_start(status_entry, true, true, 0) } end def status_entry lazy_initialize(:status_entry) { @status_entry = Gtk::Entry.new @status_entry.set_editable(false) } end def lazy_initialize(symbol) if (!instance_eval("defined?(@#{symbol.to_s})")) yield end return instance_eval("@" + symbol.to_s) end end class EnhancedProgressBar < Gtk::ProgressBar def set_style(style) super hide show end end class EnhancedLabel < Gtk::Label def set_text(text) super(text.gsub(/\n\t/, "\n" + (" " * 4))) end end class FaultListItem < Gtk::ListItem attr_reader(:fault) def initialize(fault) super(fault.short_display) @fault = fault end end end end end end if __FILE__ == $0 Test::Unit::UI::GTK::TestRunner.start_command_line_test end PK!`Dc"c"ui/tk/testrunner.rbnu[#-- # # Original Author:: Nathaniel Talbott. # Author:: Kazuhiro NISHIYAMA. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # Copyright:: Copyright (c) 2003 Kazuhiro NISHIYAMA. All rights reserved. # License:: Ruby license. require 'tk' require 'test/unit/ui/testrunnermediator' require 'test/unit/ui/testrunnerutilities' module Test module Unit module UI module Tk # Runs a Test::Unit::TestSuite in a Tk UI. Obviously, # this one requires you to have Tk # and the Ruby Tk extension installed. class TestRunner extend TestRunnerUtilities # Creates a new TestRunner for running the passed # suite. def initialize(suite, output_level = NORMAL) if (suite.respond_to?(:suite)) @suite = suite.suite else @suite = suite end @result = nil @red = false @fault_detail_list = [] @runner = Thread.current @restart_signal = Class.new(Exception) @viewer = Thread.start do @runner.join rescue @runner.run ::Tk.mainloop end @viewer.join rescue nil # wait deadlock to handshake end # Begins the test run. def start setup_ui setup_mediator attach_to_mediator start_ui @result end private def setup_mediator @mediator = TestRunnerMediator.new(@suite) suite_name = @suite.to_s if ( @suite.kind_of?(Module) ) suite_name = @suite.name end @suite_name_entry.value = suite_name end def attach_to_mediator @run_button.command(method(:run_test)) @fault_list.bind('ButtonPress-1', proc{|y| fault = @fault_detail_list[@fault_list.nearest(y)] if fault show_fault(fault) end }, '%y') @mediator.add_listener(TestRunnerMediator::RESET, &method(:reset_ui)) @mediator.add_listener(TestResult::FAULT, &method(:add_fault)) @mediator.add_listener(TestResult::CHANGED, &method(:result_changed)) @mediator.add_listener(TestRunnerMediator::STARTED, &method(:started)) @mediator.add_listener(TestCase::STARTED, &method(:test_started)) @mediator.add_listener(TestRunnerMediator::FINISHED, &method(:finished)) end def run_test @runner.raise(@restart_signal) end def start_ui @viewer.run running = false begin loop do if (running ^= true) @run_button.configure('text'=>'Stop') @mediator.run_suite else @run_button.configure('text'=>'Run') @viewer.join break end end rescue @restart_signal retry rescue end end def stop ::Tk.exit end def reset_ui(count) @test_total_count = count.to_f @test_progress_bar.configure('background'=>'green') @test_progress_bar.place('relwidth'=>(count.zero? ? 0 : 0/count)) @red = false @test_count_label.value = 0 @assertion_count_label.value = 0 @failure_count_label.value = 0 @error_count_label.value = 0 @fault_list.delete(0, 'end') @fault_detail_list = [] clear_fault end def add_fault(fault) if ( ! @red ) @test_progress_bar.configure('background'=>'red') @red = true end @fault_detail_list.push fault @fault_list.insert('end', fault.short_display) end def show_fault(fault) raw_show_fault(fault.long_display) end def raw_show_fault(string) @detail_text.value = string end def clear_fault raw_show_fault("") end def result_changed(result) @test_count_label.value = result.run_count @test_progress_bar.place('relwidth'=>result.run_count/@test_total_count) @assertion_count_label.value = result.assertion_count @failure_count_label.value = result.failure_count @error_count_label.value = result.error_count end def started(result) @result = result output_status("Started...") end def test_started(test_name) output_status("Running #{test_name}...") end def finished(elapsed_time) output_status("Finished in #{elapsed_time} seconds") end def output_status(string) @status_entry.value = string end def setup_ui @status_entry = TkVariable.new l = TkLabel.new(nil, 'textvariable'=>@status_entry, 'relief'=>'sunken') l.pack('side'=>'bottom', 'fill'=>'x') suite_frame = TkFrame.new.pack('fill'=>'x') @run_button = TkButton.new(suite_frame, 'text'=>'Run') @run_button.pack('side'=>'right') TkLabel.new(suite_frame, 'text'=>'Suite:').pack('side'=>'left') @suite_name_entry = TkVariable.new l = TkLabel.new(suite_frame, 'textvariable'=>@suite_name_entry, 'relief'=>'sunken') l.pack('side'=>'left', 'fill'=>'x', 'expand'=>true) f = TkFrame.new(nil, 'relief'=>'sunken', 'borderwidth'=>3, 'height'=>20).pack('fill'=>'x', 'padx'=>1) @test_progress_bar = TkFrame.new(f, 'background'=>'green').place('anchor'=>'nw', 'relwidth'=>0.0, 'relheight'=>1.0) info_frame = TkFrame.new.pack('fill'=>'x') @test_count_label = create_count_label(info_frame, 'Tests:') @assertion_count_label = create_count_label(info_frame, 'Assertions:') @failure_count_label = create_count_label(info_frame, 'Failures:') @error_count_label = create_count_label(info_frame, 'Errors:') if (::Tk.info('command', TkPanedWindow::TkCommandNames[0]) != "") # use panedwindow paned_frame = TkPanedWindow.new("orient"=>"vertical").pack('fill'=>'both', 'expand'=>true) fault_list_frame = TkFrame.new(paned_frame) detail_frame = TkFrame.new(paned_frame) paned_frame.add(fault_list_frame, detail_frame) else # no panedwindow paned_frame = nil fault_list_frame = TkFrame.new.pack('fill'=>'both', 'expand'=>true) detail_frame = TkFrame.new.pack('fill'=>'both', 'expand'=>true) end TkGrid.rowconfigure(fault_list_frame, 0, 'weight'=>1, 'minsize'=>0) TkGrid.columnconfigure(fault_list_frame, 0, 'weight'=>1, 'minsize'=>0) fault_scrollbar_y = TkScrollbar.new(fault_list_frame) fault_scrollbar_x = TkScrollbar.new(fault_list_frame) @fault_list = TkListbox.new(fault_list_frame) @fault_list.yscrollbar(fault_scrollbar_y) @fault_list.xscrollbar(fault_scrollbar_x) TkGrid.rowconfigure(detail_frame, 0, 'weight'=>1, 'minsize'=>0) TkGrid.columnconfigure(detail_frame, 0, 'weight'=>1, 'minsize'=>0) ::Tk.grid(@fault_list, fault_scrollbar_y, 'sticky'=>'news') ::Tk.grid(fault_scrollbar_x, 'sticky'=>'news') detail_scrollbar_y = TkScrollbar.new(detail_frame) detail_scrollbar_x = TkScrollbar.new(detail_frame) @detail_text = TkText.new(detail_frame, 'height'=>10, 'wrap'=>'none') { bindtags(bindtags - [TkText]) } @detail_text.yscrollbar(detail_scrollbar_y) @detail_text.xscrollbar(detail_scrollbar_x) ::Tk.grid(@detail_text, detail_scrollbar_y, 'sticky'=>'news') ::Tk.grid(detail_scrollbar_x, 'sticky'=>'news') # rubber-style pane if paned_frame ::Tk.update @height = paned_frame.winfo_height paned_frame.bind('Configure', proc{|h| paned_frame.sash_place(0, 0, paned_frame.sash_coord(0)[1] * h / @height) @height = h }, '%h') end end def create_count_label(parent, label) TkLabel.new(parent, 'text'=>label).pack('side'=>'left', 'expand'=>true) v = TkVariable.new(0) TkLabel.new(parent, 'textvariable'=>v).pack('side'=>'left', 'expand'=>true) v end end end end end end if __FILE__ == $0 Test::Unit::UI::Tk::TestRunner.start_command_line_test end PK!Kui/testrunnerutilities.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # License:: Ruby license. module Test module Unit module UI SILENT = 0 PROGRESS_ONLY = 1 NORMAL = 2 VERBOSE = 3 # Provides some utilities common to most, if not all, # TestRunners. # #-- # # Perhaps there ought to be a TestRunner superclass? There # seems to be a decent amount of shared code between test # runners. module TestRunnerUtilities # Creates a new TestRunner and runs the suite. def run(suite, output_level=NORMAL) return new(suite, output_level).start end # Takes care of the ARGV parsing and suite # determination necessary for running one of the # TestRunners from the command line. def start_command_line_test if ARGV.empty? puts "You should supply the name of a test suite file to the runner" exit end require ARGV[0].gsub(/.+::/, '') new(eval(ARGV[0])).start end end end end end PK!2>>ui/gtk2/testrunner.rbnu[#-- # # Author:: Kenta MURATA. # Copyright:: Copyright (c) 2000-2002 Kenta MURATA. All rights reserved. # License:: Ruby license. require "gtk2" require "test/unit/ui/testrunnermediator" require "test/unit/ui/testrunnerutilities" module Test module Unit module UI module GTK2 Gtk.init class EnhancedLabel < Gtk::Label def set_text(text) super(text.gsub(/\n\t/, "\n ")) end end class FaultList < Gtk::TreeView def initialize @faults = [] @model = Gtk::ListStore.new(String, String) super(@model) column = Gtk::TreeViewColumn.new column.visible = false append_column(column) renderer = Gtk::CellRendererText.new column = Gtk::TreeViewColumn.new("Failures", renderer, {:text => 1}) append_column(column) selection.mode = Gtk::SELECTION_SINGLE set_rules_hint(true) set_headers_visible(false) end # def initialize def add_fault(fault) @faults.push(fault) iter = @model.append iter.set_value(0, (@faults.length - 1).to_s) iter.set_value(1, fault.short_display) end # def add_fault(fault) def get_fault(iter) @faults[iter.get_value(0).to_i] end # def get_fault def clear model.clear end # def clear end class TestRunner extend TestRunnerUtilities def lazy_initialize(symbol) if !instance_eval("defined?(@#{symbol})") then yield end return instance_eval("@#{symbol}") end private :lazy_initialize def status_entry lazy_initialize(:status_entry) do @status_entry = Gtk::Entry.new @status_entry.editable = false end end private :status_entry def status_panel lazy_initialize(:status_panel) do @status_panel = Gtk::HBox.new @status_panel.border_width = 10 @status_panel.pack_start(status_entry, true, true, 0) end end private :status_panel def fault_detail_label lazy_initialize(:fault_detail_label) do @fault_detail_label = EnhancedLabel.new("") # style = Gtk::Style.new # font = Gdk::Font. # font_load("-*-Courier 10 Pitch-medium-r-normal--*-120-*-*-*-*-*-*") # style.set_font(font) # @fault_detail_label.style = style @fault_detail_label.justify = Gtk::JUSTIFY_LEFT @fault_detail_label.wrap = false end end private :fault_detail_label def inner_detail_sub_panel lazy_initialize(:inner_detail_sub_panel) do @inner_detail_sub_panel = Gtk::HBox.new @inner_detail_sub_panel.pack_start(fault_detail_label, false, false, 0) end end private :inner_detail_sub_panel def outer_detail_sub_panel lazy_initialize(:outer_detail_sub_panel) do @outer_detail_sub_panel = Gtk::VBox.new @outer_detail_sub_panel.pack_start(inner_detail_sub_panel, false, false, 0) end end private :outer_detail_sub_panel def detail_scrolled_window lazy_initialize(:detail_scrolled_window) do @detail_scrolled_window = Gtk::ScrolledWindow.new @detail_scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC) @detail_scrolled_window. set_size_request(400, @detail_scrolled_window.allocation.height) @detail_scrolled_window.add_with_viewport(outer_detail_sub_panel) end end private :detail_scrolled_window def detail_panel lazy_initialize(:detail_panel) do @detail_panel = Gtk::HBox.new @detail_panel.border_width = 10 @detail_panel.pack_start(detail_scrolled_window, true, true, 0) end end private :detail_panel def fault_list lazy_initialize(:fault_list) do @fault_list = FaultList.new end end private :fault_list def list_scrolled_window lazy_initialize(:list_scrolled_window) do @list_scrolled_window = Gtk::ScrolledWindow.new @list_scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC) @list_scrolled_window. set_size_request(@list_scrolled_window.allocation.width, 150) @list_scrolled_window.add_with_viewport(fault_list) end end private :list_scrolled_window def list_panel lazy_initialize(:list_panel) do @list_panel = Gtk::HBox.new @list_panel.border_width = 10 @list_panel.pack_start(list_scrolled_window, true, true, 0) end end private :list_panel def error_count_label lazy_initialize(:error_count_label) do @error_count_label = Gtk::Label.new("0") @error_count_label.justify = Gtk::JUSTIFY_LEFT end end private :error_count_label def failure_count_label lazy_initialize(:failure_count_label) do @failure_count_label = Gtk::Label.new("0") @failure_count_label.justify = Gtk::JUSTIFY_LEFT end end private :failure_count_label def assertion_count_label lazy_initialize(:assertion_count_label) do @assertion_count_label = Gtk::Label.new("0") @assertion_count_label.justify = Gtk::JUSTIFY_LEFT end end private :assertion_count_label def run_count_label lazy_initialize(:run_count_label) do @run_count_label = Gtk::Label.new("0") @run_count_label.justify = Gtk::JUSTIFY_LEFT end end private :run_count_label def info_panel lazy_initialize(:info_panel) do @info_panel = Gtk::HBox.new(false, 0) @info_panel.border_width = 10 @info_panel.pack_start(Gtk::Label.new("Runs:"), false, false, 0) @info_panel.pack_start(run_count_label, true, false, 0) @info_panel.pack_start(Gtk::Label.new("Assertions:"), false, false, 0) @info_panel.pack_start(assertion_count_label, true, false, 0) @info_panel.pack_start(Gtk::Label.new("Failures:"), false, false, 0) @info_panel.pack_start(failure_count_label, true, false, 0) @info_panel.pack_start(Gtk::Label.new("Errors:"), false, false, 0) @info_panel.pack_start(error_count_label, true, false, 0) end end # def info_panel private :info_panel def green_style lazy_initialize(:green_style) do @green_style = Gtk::Style.new @green_style.set_bg(Gtk::STATE_PRELIGHT, 0x0000, 0xFFFF, 0x0000) end end # def green_style private :green_style def red_style lazy_initialize(:red_style) do @red_style = Gtk::Style.new @red_style.set_bg(Gtk::STATE_PRELIGHT, 0xFFFF, 0x0000, 0x0000) end end # def red_style private :red_style def test_progress_bar lazy_initialize(:test_progress_bar) { @test_progress_bar = Gtk::ProgressBar.new @test_progress_bar.fraction = 0.0 @test_progress_bar. set_size_request(@test_progress_bar.allocation.width, info_panel.size_request[1]) @test_progress_bar.style = green_style } end # def test_progress_bar private :test_progress_bar def progress_panel lazy_initialize(:progress_panel) do @progress_panel = Gtk::HBox.new(false, 10) @progress_panel.border_width = 10 @progress_panel.pack_start(test_progress_bar, true, true, 0) end end # def progress_panel def run_button lazy_initialize(:run_button) do @run_button = Gtk::Button.new("Run") end end # def run_button def suite_name_entry lazy_initialize(:suite_name_entry) do @suite_name_entry = Gtk::Entry.new @suite_name_entry.editable = false end end # def suite_name_entry private :suite_name_entry def suite_panel lazy_initialize(:suite_panel) do @suite_panel = Gtk::HBox.new(false, 10) @suite_panel.border_width = 10 @suite_panel.pack_start(Gtk::Label.new("Suite:"), false, false, 0) @suite_panel.pack_start(suite_name_entry, true, true, 0) @suite_panel.pack_start(run_button, false, false, 0) end end # def suite_panel private :suite_panel def main_panel lazy_initialize(:main_panel) do @main_panel = Gtk::VBox.new(false, 0) @main_panel.pack_start(suite_panel, false, false, 0) @main_panel.pack_start(progress_panel, false, false, 0) @main_panel.pack_start(info_panel, false, false, 0) @main_panel.pack_start(list_panel, false, false, 0) @main_panel.pack_start(detail_panel, true, true, 0) @main_panel.pack_start(status_panel, false, false, 0) end end # def main_panel private :main_panel def main_window lazy_initialize(:main_window) do @main_window = Gtk::Window.new(Gtk::Window::TOPLEVEL) @main_window.set_title("Test::Unit TestRunner") @main_window.set_default_size(800, 600) @main_window.set_resizable(true) @main_window.add(main_panel) end end # def main_window private :main_window def setup_ui main_window.signal_connect("destroy", nil) { stop } main_window.show_all fault_list.selection.signal_connect("changed", nil) do |selection, data| if selection.selected then show_fault(fault_list.get_fault(selection.selected)) else clear_fault end end end # def setup_ui private :setup_ui def output_status(string) status_entry.set_text(string) end # def output_status(string) private :output_status def finished(elapsed_time) test_progress_bar.fraction = 1.0 output_status("Finished in #{elapsed_time} seconds") end # def finished(elapsed_time) private :finished def test_started(test_name) output_status("Running #{test_name}...") end # def test_started(test_name) private :test_started def started(result) @result = result output_status("Started...") end # def started(result) private :started def test_finished(result) test_progress_bar.fraction += 1.0 / @count end # def test_finished(result) def result_changed(result) run_count_label.label = result.run_count.to_s assertion_count_label.label = result.assertion_count.to_s failure_count_label.label = result.failure_count.to_s error_count_label.label = result.error_count.to_s end # def result_changed(result) private :result_changed def clear_fault raw_show_fault("") end # def clear_fault private :clear_fault def raw_show_fault(string) fault_detail_label.set_text(string) outer_detail_sub_panel.queue_resize end # def raw_show_fault(string) private :raw_show_fault def show_fault(fault) raw_show_fault(fault.long_display) end # def show_fault(fault) private :show_fault def add_fault(fault) if not @red then test_progress_bar.style = red_style @red = true end fault_list.add_fault(fault) end # def add_fault(fault) private :add_fault def reset_ui(count) test_progress_bar.style = green_style test_progress_bar.fraction = 0.0 @count = count + 1 @red = false run_count_label.set_text("0") assertion_count_label.set_text("0") failure_count_label.set_text("0") error_count_label.set_text("0") fault_list.clear end # def reset_ui(count) private :reset_ui def stop Gtk.main_quit end # def stop private :stop def run_test @runner.raise(@restart_signal) end private :run_test def start_ui @viewer.run running = false begin loop do if (running ^= true) run_button.child.text = "Stop" @mediator.run_suite else run_button.child.text = "Run" @viewer.join break end end rescue @restart_signal retry rescue end end # def start_ui private :start_ui def attach_to_mediator run_button.signal_connect("clicked", nil) { run_test } @mediator.add_listener(TestRunnerMediator::RESET, &method(:reset_ui)) @mediator.add_listener(TestRunnerMediator::STARTED, &method(:started)) @mediator.add_listener(TestRunnerMediator::FINISHED, &method(:finished)) @mediator.add_listener(TestResult::FAULT, &method(:add_fault)) @mediator.add_listener(TestResult::CHANGED, &method(:result_changed)) @mediator.add_listener(TestCase::STARTED, &method(:test_started)) @mediator.add_listener(TestCase::FINISHED, &method(:test_finished)) end # def attach_to_mediator private :attach_to_mediator def setup_mediator @mediator = TestRunnerMediator.new(@suite) suite_name = @suite.to_s if @suite.kind_of?(Module) then suite_name = @suite.name end suite_name_entry.set_text(suite_name) end # def setup_mediator private :setup_mediator def start setup_mediator setup_ui attach_to_mediator start_ui @result end # def start def initialize(suite, output_level = NORMAL) if suite.respond_to?(:suite) then @suite = suite.suite else @suite = suite end @result = nil @runner = Thread.current @restart_signal = Class.new(Exception) @viewer = Thread.start do @runner.join rescue @runner.run Gtk.main end @viewer.join rescue nil # wait deadlock to handshake end # def initialize(suite) end # class TestRunner end # module GTK2 end # module UI end # module Unit end # module Test PK! 000ui/testrunnermediator.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # License:: Ruby license. require 'test/unit' require 'test/unit/util/observable' require 'test/unit/testresult' module Test module Unit module UI # Provides an interface to write any given UI against, # hopefully making it easy to write new UIs. class TestRunnerMediator RESET = name + "::RESET" STARTED = name + "::STARTED" FINISHED = name + "::FINISHED" include Util::Observable # Creates a new TestRunnerMediator initialized to run # the passed suite. def initialize(suite) @suite = suite end # Runs the suite the TestRunnerMediator was created # with. def run_suite Unit.run = true begin_time = Time.now notify_listeners(RESET, @suite.size) result = create_result notify_listeners(STARTED, result) result_listener = result.add_listener(TestResult::CHANGED) do |updated_result| notify_listeners(TestResult::CHANGED, updated_result) end fault_listener = result.add_listener(TestResult::FAULT) do |fault| notify_listeners(TestResult::FAULT, fault) end @suite.run(result) do |channel, value| notify_listeners(channel, value) end result.remove_listener(TestResult::FAULT, fault_listener) result.remove_listener(TestResult::CHANGED, result_listener) end_time = Time.now elapsed_time = end_time - begin_time notify_listeners(FINISHED, elapsed_time) #"Finished in #{elapsed_time} seconds.") return result end private # A factory method to create the result the mediator # should run with. Can be overridden by subclasses if # one wants to use a different result. def create_result return TestResult.new end end end end end PK!\~!~!ui/fox/testrunner.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # License:: Ruby license. require 'fox' require 'test/unit/ui/testrunnermediator' require 'test/unit/ui/testrunnerutilities' include Fox module Test module Unit module UI module Fox # Runs a Test::Unit::TestSuite in a Fox UI. Obviously, # this one requires you to have Fox # (http://www.fox-toolkit.org/fox.html) and the Ruby # Fox extension (http://fxruby.sourceforge.net/) # installed. class TestRunner extend TestRunnerUtilities RED_STYLE = FXRGBA(0xFF,0,0,0xFF) #0xFF000000 GREEN_STYLE = FXRGBA(0,0xFF,0,0xFF) #0x00FF0000 # Creates a new TestRunner for running the passed # suite. def initialize(suite, output_level = NORMAL) if (suite.respond_to?(:suite)) @suite = suite.suite else @suite = suite end @result = nil @red = false end # Begins the test run. def start setup_ui setup_mediator attach_to_mediator start_ui @result end def setup_mediator @mediator = TestRunnerMediator.new(@suite) suite_name = @suite.to_s if ( @suite.kind_of?(Module) ) suite_name = @suite.name end @suite_name_entry.text = suite_name end def attach_to_mediator @mediator.add_listener(TestRunnerMediator::RESET, &method(:reset_ui)) @mediator.add_listener(TestResult::FAULT, &method(:add_fault)) @mediator.add_listener(TestResult::CHANGED, &method(:result_changed)) @mediator.add_listener(TestRunnerMediator::STARTED, &method(:started)) @mediator.add_listener(TestCase::STARTED, &method(:test_started)) @mediator.add_listener(TestRunnerMediator::FINISHED, &method(:finished)) end def start_ui @application.create @window.show(PLACEMENT_SCREEN) @application.addTimeout(1) do @mediator.run_suite end @application.run end def stop @application.exit(0) end def reset_ui(count) @test_progress_bar.barColor = GREEN_STYLE @test_progress_bar.total = count @test_progress_bar.progress = 0 @red = false @test_count_label.text = "0" @assertion_count_label.text = "0" @failure_count_label.text = "0" @error_count_label.text = "0" @fault_list.clearItems end def add_fault(fault) if ( ! @red ) @test_progress_bar.barColor = RED_STYLE @red = true end item = FaultListItem.new(fault) @fault_list.appendItem(item) end def show_fault(fault) raw_show_fault(fault.long_display) end def raw_show_fault(string) @detail_text.setText(string) end def clear_fault raw_show_fault("") end def result_changed(result) @test_progress_bar.progress = result.run_count @test_count_label.text = result.run_count.to_s @assertion_count_label.text = result.assertion_count.to_s @failure_count_label.text = result.failure_count.to_s @error_count_label.text = result.error_count.to_s # repaint now! @info_panel.repaint @application.flush end def started(result) @result = result output_status("Started...") end def test_started(test_name) output_status("Running #{test_name}...") end def finished(elapsed_time) output_status("Finished in #{elapsed_time} seconds") end def output_status(string) @status_entry.text = string @status_entry.repaint end def setup_ui @application = create_application create_tooltip(@application) @window = create_window(@application) @status_entry = create_entry(@window) main_panel = create_main_panel(@window) suite_panel = create_suite_panel(main_panel) create_label(suite_panel, "Suite:") @suite_name_entry = create_entry(suite_panel) create_button(suite_panel, "&Run\tRun the current suite", proc { @mediator.run_suite }) @test_progress_bar = create_progress_bar(main_panel) @info_panel = create_info_panel(main_panel) create_label(@info_panel, "Tests:") @test_count_label = create_label(@info_panel, "0") create_label(@info_panel, "Assertions:") @assertion_count_label = create_label(@info_panel, "0") create_label(@info_panel, "Failures:") @failure_count_label = create_label(@info_panel, "0") create_label(@info_panel, "Errors:") @error_count_label = create_label(@info_panel, "0") list_panel = create_list_panel(main_panel) @fault_list = create_fault_list(list_panel) detail_panel = create_detail_panel(main_panel) @detail_text = create_text(detail_panel) end def create_application app = FXApp.new("TestRunner", "Test::Unit") app.init([]) app end def create_window(app) FXMainWindow.new(app, "Test::Unit TestRunner", nil, nil, DECOR_ALL, 0, 0, 450) end def create_tooltip(app) FXTooltip.new(app) end def create_main_panel(parent) panel = FXVerticalFrame.new(parent, LAYOUT_FILL_X | LAYOUT_FILL_Y) panel.vSpacing = 10 panel end def create_suite_panel(parent) FXHorizontalFrame.new(parent, LAYOUT_SIDE_LEFT | LAYOUT_FILL_X) end def create_button(parent, text, action) FXButton.new(parent, text).connect(SEL_COMMAND, &action) end def create_progress_bar(parent) FXProgressBar.new(parent, nil, 0, PROGRESSBAR_NORMAL | LAYOUT_FILL_X) end def create_info_panel(parent) FXMatrix.new(parent, 1, MATRIX_BY_ROWS | LAYOUT_FILL_X) end def create_label(parent, text) FXLabel.new(parent, text, nil, JUSTIFY_CENTER_X | LAYOUT_FILL_COLUMN) end def create_list_panel(parent) FXHorizontalFrame.new(parent, LAYOUT_FILL_X | FRAME_SUNKEN | FRAME_THICK) end def create_fault_list(parent) list = FXList.new(parent, 10, nil, 0, LIST_SINGLESELECT | LAYOUT_FILL_X) #, 0, 0, 0, 150) list.connect(SEL_COMMAND) do |sender, sel, ptr| if sender.retrieveItem(sender.currentItem).selected? show_fault(sender.retrieveItem(sender.currentItem).fault) else clear_fault end end list end def create_detail_panel(parent) FXHorizontalFrame.new(parent, LAYOUT_FILL_X | LAYOUT_FILL_Y | FRAME_SUNKEN | FRAME_THICK) end def create_text(parent) FXText.new(parent, nil, 0, TEXT_READONLY | LAYOUT_FILL_X | LAYOUT_FILL_Y) end def create_entry(parent) entry = FXTextField.new(parent, 30, nil, 0, TEXTFIELD_NORMAL | LAYOUT_SIDE_BOTTOM | LAYOUT_FILL_X) entry.disable entry end end class FaultListItem < FXListItem attr_reader(:fault) def initialize(fault) super(fault.short_display) @fault = fault end end end end end end if __FILE__ == $0 Test::Unit::UI::Fox::TestRunner.start_command_line_test end PK!&& failure.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # License:: Ruby license. module Test module Unit # Encapsulates a test failure. Created by Test::Unit::TestCase # when an assertion fails. class Failure attr_reader :test_name, :location, :message SINGLE_CHARACTER = 'F' # Creates a new Failure with the given location and # message. def initialize(test_name, location, message) @test_name = test_name @location = location @message = message end # Returns a single character representation of a failure. def single_character_display SINGLE_CHARACTER end # Returns a brief version of the error description. def short_display "#@test_name: #{@message.split("\n")[0]}" end # Returns a verbose version of the error description. def long_display location_display = if(location.size == 1) location[0].sub(/\A(.+:\d+).*/, ' [\\1]') else "\n [#{location.join("\n ")}]" end "Failure:\n#@test_name#{location_display}:\n#@message" end # Overridden to return long_display. def to_s long_display end end end end PK!util/backtracefilter.rbnu[module Test module Unit module Util module BacktraceFilter TESTUNIT_FILE_SEPARATORS = %r{[\\/:]} TESTUNIT_PREFIX = __FILE__.split(TESTUNIT_FILE_SEPARATORS)[0..-3] TESTUNIT_RB_FILE = /\.rb\Z/ def filter_backtrace(backtrace, prefix=nil) return ["No backtrace"] unless(backtrace) split_p = if(prefix) prefix.split(TESTUNIT_FILE_SEPARATORS) else TESTUNIT_PREFIX end match = proc do |e| split_e = e.split(TESTUNIT_FILE_SEPARATORS)[0, split_p.size] next false unless(split_e[0..-2] == split_p[0..-2]) split_e[-1].sub(TESTUNIT_RB_FILE, '') == split_p[-1] end return backtrace unless(backtrace.detect(&match)) found_prefix = false new_backtrace = backtrace.reverse.reject do |e| if(match[e]) found_prefix = true true elsif(found_prefix) false else true end end.reverse new_backtrace = (new_backtrace.empty? ? backtrace : new_backtrace) new_backtrace = new_backtrace.reject(&match) new_backtrace.empty? ? backtrace : new_backtrace end end end end end PK!y3 3 util/observable.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # License:: Ruby license. require 'test/unit/util/procwrapper' module Test module Unit module Util # This is a utility class that allows anything mixing # it in to notify a set of listeners about interesting # events. module Observable # We use this for defaults since nil might mean something NOTHING = "NOTHING/#{__id__}" # Adds the passed proc as a listener on the # channel indicated by channel_name. listener_key # is used to remove the listener later; if none is # specified, the proc itself is used. # # Whatever is used as the listener_key is # returned, making it very easy to use the proc # itself as the listener_key: # # listener = add_listener("Channel") { ... } # remove_listener("Channel", listener) def add_listener(channel_name, listener_key=NOTHING, &listener) # :yields: value unless(block_given?) raise ArgumentError.new("No callback was passed as a listener") end key = listener_key if (listener_key == NOTHING) listener_key = listener key = ProcWrapper.new(listener) end channels[channel_name] ||= {} channels[channel_name][key] = listener return listener_key end # Removes the listener indicated by listener_key # from the channel indicated by # channel_name. Returns the registered proc, or # nil if none was found. def remove_listener(channel_name, listener_key) channel = channels[channel_name] return nil unless (channel) key = listener_key if (listener_key.instance_of?(Proc)) key = ProcWrapper.new(listener_key) end if (channel.has_key?(key)) return channel.delete(key) end return nil end # Calls all the procs registered on the channel # indicated by channel_name. If value is # specified, it is passed in to the procs, # otherwise they are called with no arguments. # #-- # # Perhaps this should be private? Would it ever # make sense for an external class to call this # method directly? def notify_listeners(channel_name, *arguments) channel = channels[channel_name] return 0 unless (channel) listeners = channel.values listeners.each { |listener| listener.call(*arguments) } return listeners.size end private def channels @channels ||= {} return @channels end end end end end PK!}hUUutil/procwrapper.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # License:: Ruby license. module Test module Unit module Util # Allows the storage of a Proc passed through '&' in a # hash. # # Note: this may be inefficient, since the hash being # used is not necessarily very good. In Observable, # efficiency is not too important, since the hash is # only accessed when adding and removing listeners, # not when notifying. class ProcWrapper # Creates a new wrapper for a_proc. def initialize(a_proc) @a_proc = a_proc @hash = a_proc.inspect.sub(/^(#<#{a_proc.class}:)/){''}.sub(/(>)$/){''}.hex end def hash return @hash end def ==(other) case(other) when ProcWrapper return @a_proc == other.to_proc else return super end end alias :eql? :== def to_proc return @a_proc end end end end end PK! J))assertionfailederror.rbnu[#-- # # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # License:: Ruby license. module Test module Unit # Thrown by Test::Unit::Assertions when an assertion fails. class AssertionFailedError < StandardError end end end PK!ݮ?3G3G assertions.rbnu[# Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved. # License:: Ruby license. require 'test/unit/assertionfailederror' require 'test/unit/util/backtracefilter' module Test module Unit ## # Test::Unit::Assertions contains the standard Test::Unit assertions. # Assertions is included in Test::Unit::TestCase. # # To include it in your own code and use its functionality, you simply # need to rescue Test::Unit::AssertionFailedError. Additionally you may # override add_assertion to get notified whenever an assertion is made. # # Notes: # * The message to each assertion, if given, will be propagated with the # failure. # * It is easy to add your own assertions based on assert_block(). # # = Example Custom Assertion # # def deny(boolean, message = nil) # message = build_message message, ' is not false or nil.', boolean # assert_block message do # not boolean # end # end module Assertions ## # The assertion upon which all other assertions are based. Passes if the # block yields true. # # Example: # assert_block "Couldn't do the thing" do # do_the_thing # end public def assert_block(message="assert_block failed.") # :yields: _wrap_assertion do if (! yield) raise AssertionFailedError.new(message.to_s) end end end ## # Asserts that +boolean+ is not false or nil. # # Example: # assert [1, 2].include?(5) public def assert(boolean, message=nil) _wrap_assertion do assert_block("assert should not be called with a block.") { !block_given? } assert_block(build_message(message, " is not true.", boolean)) { boolean } end end ## # Passes if +expected+ == +actual. # # Note that the ordering of arguments is important, since a helpful # error message is generated when this one fails that tells you the # values of expected and actual. # # Example: # assert_equal 'MY STRING', 'my string'.upcase public def assert_equal(expected, actual, message=nil) full_message = build_message(message, < expected but was . EOT assert_block(full_message) { expected == actual } end private def _check_exception_class(args) # :nodoc: args.partition do |klass| next if klass.instance_of?(Module) assert(Exception >= klass, "Should expect a class of exception, #{klass}") true end end private def _expected_exception?(actual_exception, exceptions, modules) # :nodoc: exceptions.include?(actual_exception.class) or modules.any? {|mod| actual_exception.is_a?(mod)} end ## # Passes if the block raises one of the given exceptions. # # Example: # assert_raise RuntimeError, LoadError do # raise 'Boom!!!' # end public def assert_raise(*args) _wrap_assertion do if Module === args.last message = "" else message = args.pop end exceptions, modules = _check_exception_class(args) expected = args.size == 1 ? args.first : args actual_exception = nil full_message = build_message(message, " exception expected but none was thrown.", expected) assert_block(full_message) do begin yield rescue Exception => actual_exception break end false end full_message = build_message(message, " exception expected but was\n?", expected, actual_exception) assert_block(full_message) {_expected_exception?(actual_exception, exceptions, modules)} actual_exception end end ## # Alias of assert_raise. # # Will be deprecated in 1.9, and removed in 2.0. public def assert_raises(*args, &block) assert_raise(*args, &block) end ## # Passes if +object+ .instance_of? +klass+ # # Example: # assert_instance_of String, 'foo' public def assert_instance_of(klass, object, message="") _wrap_assertion do assert_equal(Class, klass.class, "assert_instance_of takes a Class as its first argument") full_message = build_message(message, < expected to be an instance of but was . EOT assert_block(full_message){object.instance_of?(klass)} end end ## # Passes if +object+ is nil. # # Example: # assert_nil [1, 2].uniq! public def assert_nil(object, message="") assert_equal(nil, object, message) end ## # Passes if +object+ .kind_of? +klass+ # # Example: # assert_kind_of Object, 'foo' public def assert_kind_of(klass, object, message="") _wrap_assertion do assert(klass.kind_of?(Module), "The first parameter to assert_kind_of should be a kind_of Module.") full_message = build_message(message, "\nexpected to be kind_of\\?\n but was\n.", object, klass, object.class) assert_block(full_message){object.kind_of?(klass)} end end ## # Passes if +object+ .respond_to? +method+ # # Example: # assert_respond_to 'bugbear', :slice public def assert_respond_to(object, method, message="") _wrap_assertion do full_message = build_message(nil, "\ngiven as the method name argument to #assert_respond_to must be a Symbol or #respond_to\\?(:to_str).", method) assert_block(full_message) do method.kind_of?(Symbol) || method.respond_to?(:to_str) end full_message = build_message(message, < of type expected to respond_to\\?. EOT assert_block(full_message) { object.respond_to?(method) } end end ## # Passes if +string+ =~ +pattern+. # # Example: # assert_match(/\d+/, 'five, 6, seven') public def assert_match(pattern, string, message="") _wrap_assertion do pattern = case(pattern) when String Regexp.new(Regexp.escape(pattern)) else pattern end full_message = build_message(message, " expected to be =~\n.", string, pattern) assert_block(full_message) { string =~ pattern } end end ## # Passes if +actual+ .equal? +expected+ (i.e. they are the same # instance). # # Example: # o = Object.new # assert_same o, o public def assert_same(expected, actual, message="") full_message = build_message(message, < with id expected to be equal\\? to with id . EOT assert_block(full_message) { actual.equal?(expected) } end ## # Compares the +object1+ with +object2+ using +operator+. # # Passes if object1.__send__(operator, object2) is true. # # Example: # assert_operator 5, :>=, 4 public def assert_operator(object1, operator, object2, message="") _wrap_assertion do full_message = build_message(nil, "\ngiven as the operator for #assert_operator must be a Symbol or #respond_to\\?(:to_str).", operator) assert_block(full_message){operator.kind_of?(Symbol) || operator.respond_to?(:to_str)} full_message = build_message(message, < expected to be ? . EOT assert_block(full_message) { object1.__send__(operator, object2) } end end ## # Passes if block does not raise an exception. # # Example: # assert_nothing_raised do # [1, 2].uniq # end public def assert_nothing_raised(*args) _wrap_assertion do if Module === args.last message = "" else message = args.pop end exceptions, modules = _check_exception_class(args) begin yield rescue Exception => e if ((args.empty? && !e.instance_of?(AssertionFailedError)) || _expected_exception?(e, exceptions, modules)) assert_block(build_message(message, "Exception raised:\n?", e)){false} else raise end end nil end end ## # Flunk always fails. # # Example: # flunk 'Not done testing yet.' public def flunk(message="Flunked") assert_block(build_message(message)){false} end ## # Passes if ! +actual+ .equal? +expected+ # # Example: # assert_not_same Object.new, Object.new public def assert_not_same(expected, actual, message="") full_message = build_message(message, < with id expected to not be equal\\? to with id . EOT assert_block(full_message) { !actual.equal?(expected) } end ## # Passes if +expected+ != +actual+ # # Example: # assert_not_equal 'some string', 5 public def assert_not_equal(expected, actual, message="") full_message = build_message(message, " expected to be != to\n.", expected, actual) assert_block(full_message) { expected != actual } end ## # Passes if ! +object+ .nil? # # Example: # assert_not_nil '1 two 3'.sub!(/two/, '2') public def assert_not_nil(object, message="") full_message = build_message(message, " expected to not be nil.", object) assert_block(full_message){!object.nil?} end ## # Passes if +regexp+ !~ +string+ # # Example: # assert_no_match(/two/, 'one 2 three') public def assert_no_match(regexp, string, message="") _wrap_assertion do assert_instance_of(Regexp, regexp, "The first argument to assert_no_match should be a Regexp.") full_message = build_message(message, " expected to not match\n.", regexp, string) assert_block(full_message) { regexp !~ string } end end UncaughtThrow = {NameError => /^uncaught throw \`(.+)\'$/, ThreadError => /^uncaught throw \`(.+)\' in thread /} #` ## # Passes if the block throws +expected_symbol+ # # Example: # assert_throws :done do # throw :done # end public def assert_throws(expected_symbol, message="", &proc) _wrap_assertion do assert_instance_of(Symbol, expected_symbol, "assert_throws expects the symbol that should be thrown for its first argument") assert_block("Should have passed a block to assert_throws."){block_given?} caught = true begin catch(expected_symbol) do proc.call caught = false end full_message = build_message(message, " should have been thrown.", expected_symbol) assert_block(full_message){caught} rescue NameError, ThreadError => error if UncaughtThrow[error.class] !~ error.message raise error end full_message = build_message(message, " expected to be thrown but\n was thrown.", expected_symbol, $1.intern) flunk(full_message) end end end ## # Passes if block does not throw anything. # # Example: # assert_nothing_thrown do # [1, 2].uniq # end public def assert_nothing_thrown(message="", &proc) _wrap_assertion do assert(block_given?, "Should have passed a block to assert_nothing_thrown") begin proc.call rescue NameError, ThreadError => error if UncaughtThrow[error.class] !~ error.message raise error end full_message = build_message(message, " was thrown when nothing was expected", $1.intern) flunk(full_message) end assert(true, "Expected nothing to be thrown") end end ## # Passes if +expected_float+ and +actual_float+ are equal # within +delta+ tolerance. # # Example: # assert_in_delta 0.05, (50000.0 / 10**6), 0.00001 public def assert_in_delta(expected_float, actual_float, delta, message="") _wrap_assertion do {expected_float => "first float", actual_float => "second float", delta => "delta"}.each do |float, name| assert_respond_to(float, :to_f, "The arguments must respond to to_f; the #{name} did not") end assert_operator(delta, :>=, 0.0, "The delta should not be negative") full_message = build_message(message, < and expected to be within of each other. EOT assert_block(full_message) { (expected_float.to_f - actual_float.to_f).abs <= delta.to_f } end end ## # Passes if the method send returns a true value. # # +send_array+ is composed of: # * A receiver # * A method # * Arguments to the method # # Example: # assert_send [[1, 2], :include?, 4] public def assert_send(send_array, message="") _wrap_assertion do assert_instance_of(Array, send_array, "assert_send requires an array of send information") assert(send_array.size >= 2, "assert_send requires at least a receiver and a message name") full_message = build_message(message, < expected to respond to with a true value. EOT assert_block(full_message) { send_array[0].__send__(send_array[1], *send_array[2..-1]) } end end ## # Builds a failure message. +head+ is added before the +template+ and # +arguments+ replaces the '?'s positionally in the template. public def build_message(head, template=nil, *arguments) template &&= template.chomp return AssertionMessage.new(head, template, arguments) end private def _wrap_assertion @_assertion_wrapped ||= false unless (@_assertion_wrapped) @_assertion_wrapped = true begin add_assertion return yield ensure @_assertion_wrapped = false end else return yield end end ## # Called whenever an assertion is made. Define this in classes that # include Test::Unit::Assertions to record assertion counts. private def add_assertion end ## # Select whether or not to use the pretty-printer. If this option is set # to false before any assertions are made, pp.rb will not be required. public def self.use_pp=(value) AssertionMessage.use_pp = value end # :stopdoc: class AssertionMessage @use_pp = true class << self attr_accessor :use_pp end class Literal def initialize(value) @value = value end def inspect @value.to_s end end class Template def self.create(string) parts = (string ? string.scan(/(?=[^\\])\?|(?:\\\?|[^\?])+/m) : []) self.new(parts) end attr_reader :count def initialize(parts) @parts = parts @count = parts.find_all{|e| e == '?'}.size end def result(parameters) raise "The number of parameters does not match the number of substitutions." if(parameters.size != count) params = parameters.dup @parts.collect{|e| e == '?' ? params.shift : e.gsub(/\\\?/m, '?')}.join('') end end def self.literal(value) Literal.new(value) end include Util::BacktraceFilter def initialize(head, template_string, parameters) @head = head @template_string = template_string @parameters = parameters end def convert(object) case object when Exception < Message: <#{convert(object.message)}> ---Backtrace--- #{filter_backtrace(object.backtrace).join("\n")} --------------- EOM else if(self.class.use_pp) begin require 'pp' rescue LoadError self.class.use_pp = false return object.inspect end unless(defined?(PP)) PP.pp(object, '').chomp else object.inspect end end end def template @template ||= Template.create(@template_string) end def add_period(string) (string =~ /\.\Z/ ? string : string + '.') end def to_s message_parts = [] if (@head) head = @head.to_s unless(head.empty?) message_parts << add_period(head) end end tail = template.result(@parameters.collect{|e| convert(e)}) message_parts << tail unless(tail.empty?) message_parts.join("\n") end end # :startdoc: end end end PK!=!n n collector/dir.rbnu[require 'test/unit/testsuite' require 'test/unit/collector' module Test module Unit module Collector class Dir include Collector attr_reader :pattern, :exclude attr_accessor :base def initialize(dir=::Dir, file=::File, object_space=::ObjectSpace, req=nil) super() @dir = dir @file = file @object_space = object_space @req = req @pattern = [/\btest_.*\.rb\Z/m] @exclude = [] end def collect(*from) basedir = @base $:.push(basedir) if basedir if(from.empty?) recursive_collect('.', find_test_cases) elsif(from.size == 1) recursive_collect(from.first, find_test_cases) else suites = [] from.each do |f| suite = recursive_collect(f, find_test_cases) suites << suite unless(suite.tests.empty?) end suite = TestSuite.new("[#{from.join(', ')}]") sort(suites).each{|s| suite << s} suite end ensure $:.delete_at($:.rindex(basedir)) if basedir end def find_test_cases(ignore=[]) cases = [] @object_space.each_object(Class) do |c| cases << c if(c < TestCase && !ignore.include?(c)) end ignore.concat(cases) cases end def recursive_collect(name, already_gathered) sub_suites = [] path = realdir(name) if @file.directory?(path) dir_name = name unless name == '.' @dir.entries(path).each do |e| next if(e == '.' || e == '..') e_name = dir_name ? @file.join(dir_name, e) : e if @file.directory?(realdir(e_name)) next if /\ACVS\z/ =~ e sub_suite = recursive_collect(e_name, already_gathered) sub_suites << sub_suite unless(sub_suite.empty?) else next if /~\z/ =~ e_name or /\A\.\#/ =~ e if @pattern and !@pattern.empty? next unless @pattern.any? {|pat| pat =~ e_name} end if @exclude and !@exclude.empty? next if @exclude.any? {|pat| pat =~ e_name} end collect_file(e_name, sub_suites, already_gathered) end end else collect_file(name, sub_suites, already_gathered) end suite = TestSuite.new(@file.basename(name)) sort(sub_suites).each{|s| suite << s} suite end def collect_file(name, suites, already_gathered) dir = @file.dirname(@file.expand_path(name, @base)) $:.unshift(dir) if(@req) @req.require(name) else require(name) end find_test_cases(already_gathered).each{|t| add_suite(suites, t.suite)} ensure $:.delete_at($:.rindex(dir)) if(dir) end def realdir(path) if @base @file.join(@base, path) else path end end end end end end PK!++collector/objectspace.rbnu[# Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved. # License:: Ruby license. require 'test/unit/collector' module Test module Unit module Collector class ObjectSpace include Collector NAME = 'collected from the ObjectSpace' def initialize(source=::ObjectSpace) super() @source = source end def collect(name=NAME) suite = TestSuite.new(name) sub_suites = [] @source.each_object(Class) do |klass| if(Test::Unit::TestCase > klass) add_suite(sub_suites, klass.suite) end end sort(sub_suites).each{|s| suite << s} suite end end end end end PK!K4 testresult.rbnu[#-- # Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # License:: Ruby license. require 'test/unit/util/observable' module Test module Unit # Collects Test::Unit::Failure and Test::Unit::Error so that # they can be displayed to the user. To this end, observers # can be added to it, allowing the dynamic updating of, say, a # UI. class TestResult include Util::Observable CHANGED = "CHANGED" FAULT = "FAULT" attr_reader(:run_count, :assertion_count) # Constructs a new, empty TestResult. def initialize @run_count, @assertion_count = 0, 0 @failures, @errors = Array.new, Array.new end # Records a test run. def add_run @run_count += 1 notify_listeners(CHANGED, self) end # Records a Test::Unit::Failure. def add_failure(failure) @failures << failure notify_listeners(FAULT, failure) notify_listeners(CHANGED, self) end # Records a Test::Unit::Error. def add_error(error) @errors << error notify_listeners(FAULT, error) notify_listeners(CHANGED, self) end # Records an individual assertion. def add_assertion @assertion_count += 1 notify_listeners(CHANGED, self) end # Returns a string contain the recorded runs, assertions, # failures and errors in this TestResult. def to_s "#{run_count} tests, #{assertion_count} assertions, #{failure_count} failures, #{error_count} errors" end # Returns whether or not this TestResult represents # successful completion. def passed? return @failures.empty? && @errors.empty? end # Returns the number of failures this TestResult has # recorded. def failure_count return @failures.size end # Returns the number of errors this TestResult has # recorded. def error_count return @errors.size end end end end PK!aAmVV autorunner.rbnu[require 'test/unit' require 'test/unit/ui/testrunnerutilities' require 'optparse' module Test module Unit class AutoRunner def self.run(force_standalone=false, default_dir=nil, argv=ARGV, &block) r = new(force_standalone || standalone?, &block) r.base = default_dir r.process_args(argv) r.run end def self.standalone? return false unless("-e" == $0) ObjectSpace.each_object(Class) do |klass| return false if(klass < TestCase) end true end RUNNERS = { :console => proc do |r| require 'test/unit/ui/console/testrunner' Test::Unit::UI::Console::TestRunner end, :gtk => proc do |r| require 'test/unit/ui/gtk/testrunner' Test::Unit::UI::GTK::TestRunner end, :gtk2 => proc do |r| require 'test/unit/ui/gtk2/testrunner' Test::Unit::UI::GTK2::TestRunner end, :fox => proc do |r| require 'test/unit/ui/fox/testrunner' Test::Unit::UI::Fox::TestRunner end, :tk => proc do |r| require 'test/unit/ui/tk/testrunner' Test::Unit::UI::Tk::TestRunner end, } OUTPUT_LEVELS = [ [:silent, UI::SILENT], [:progress, UI::PROGRESS_ONLY], [:normal, UI::NORMAL], [:verbose, UI::VERBOSE], ] COLLECTORS = { :objectspace => proc do |r| require 'test/unit/collector/objectspace' c = Collector::ObjectSpace.new c.filter = r.filters c.collect($0.sub(/\.rb\Z/, '')) end, :dir => proc do |r| require 'test/unit/collector/dir' c = Collector::Dir.new c.filter = r.filters c.pattern.concat(r.pattern) if(r.pattern) c.exclude.concat(r.exclude) if(r.exclude) c.base = r.base $:.push(r.base) if r.base c.collect(*(r.to_run.empty? ? ['.'] : r.to_run)) end, } attr_reader :suite attr_accessor :output_level, :filters, :to_run, :pattern, :exclude, :base, :workdir attr_writer :runner, :collector def initialize(standalone) Unit.run = true @standalone = standalone @runner = RUNNERS[:console] @collector = COLLECTORS[(standalone ? :dir : :objectspace)] @filters = [] @to_run = [] @output_level = UI::NORMAL @workdir = nil yield(self) if(block_given?) end def process_args(args = ARGV) begin options.order!(args) {|arg| @to_run << arg} rescue OptionParser::ParseError => e puts e puts options $! = nil abort else @filters << proc{false} unless(@filters.empty?) end not @to_run.empty? end def options @options ||= OptionParser.new do |o| o.banner = "Test::Unit automatic runner." o.banner << "\nUsage: #{$0} [options] [-- untouched arguments]" o.on o.on('-r', '--runner=RUNNER', RUNNERS, "Use the given RUNNER.", "(" + keyword_display(RUNNERS) + ")") do |r| @runner = r end if(@standalone) o.on('-b', '--basedir=DIR', "Base directory of test suites.") do |b| @base = b end o.on('-w', '--workdir=DIR', "Working directory to run tests.") do |w| @workdir = w end o.on('-a', '--add=TORUN', Array, "Add TORUN to the list of things to run;", "can be a file or a directory.") do |a| @to_run.concat(a) end @pattern = [] o.on('-p', '--pattern=PATTERN', Regexp, "Match files to collect against PATTERN.") do |e| @pattern << e end @exclude = [] o.on('-x', '--exclude=PATTERN', Regexp, "Ignore files to collect against PATTERN.") do |e| @exclude << e end end o.on('-n', '--name=NAME', String, "Runs tests matching NAME.", "(patterns may be used).") do |n| n = (%r{\A/(.*)/\Z} =~ n ? Regexp.new($1) : n) case n when Regexp @filters << proc{|t| n =~ t.method_name ? true : nil} else @filters << proc{|t| n == t.method_name ? true : nil} end end o.on('-t', '--testcase=TESTCASE', String, "Runs tests in TestCases matching TESTCASE.", "(patterns may be used).") do |n| n = (%r{\A/(.*)/\Z} =~ n ? Regexp.new($1) : n) case n when Regexp @filters << proc{|t| n =~ t.class.name ? true : nil} else @filters << proc{|t| n == t.class.name ? true : nil} end end o.on('-I', "--load-path=DIR[#{File::PATH_SEPARATOR}DIR...]", "Appends directory list to $LOAD_PATH.") do |dirs| $LOAD_PATH.concat(dirs.split(File::PATH_SEPARATOR)) end o.on('-v', '--verbose=[LEVEL]', OUTPUT_LEVELS, "Set the output level (default is verbose).", "(" + keyword_display(OUTPUT_LEVELS) + ")") do |l| @output_level = l || UI::VERBOSE end o.on('--', "Stop processing options so that the", "remaining options will be passed to the", "test."){o.terminate} o.on('-h', '--help', 'Display this help.'){puts o; exit} o.on_tail o.on_tail('Deprecated options:') o.on_tail('--console', 'Console runner (use --runner).') do warn("Deprecated option (--console).") @runner = RUNNERS[:console] end o.on_tail('--gtk', 'GTK runner (use --runner).') do warn("Deprecated option (--gtk).") @runner = RUNNERS[:gtk] end o.on_tail('--fox', 'Fox runner (use --runner).') do warn("Deprecated option (--fox).") @runner = RUNNERS[:fox] end o.on_tail end end def keyword_display(array) list = array.collect {|e, *| e.to_s} Array === array or list.sort! list.collect {|e| e.sub(/^(.)([A-Za-z]+)(?=\w*$)/, '\\1[\\2]')}.join(", ") end def run @suite = @collector[self] result = @runner[self] or return false Dir.chdir(@workdir) if @workdir result.run(@suite, @output_level).passed? end end end end PK!ov"Runner/NullTestResultCacheTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use PHPUnit\Framework\TestCase; use PHPUnit\Runner\BaseTestRunner; use PHPUnit\Runner\NullTestResultCache; /** * @group test-reorder * @small */ final class NullTestResultCacheTest extends TestCase { public function testHasWorkingStubs(): void { $cache = new NullTestResultCache; $cache->load(); $cache->persist(); $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $cache->getState('testName')); $this->assertSame(0.0, $cache->getTime('testName')); } } PK! eM##Runner/PhptTestCaseTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Runner; use PHPUnit\Framework\TestCase; use PHPUnit\Util\PHP\AbstractPhpProcess; /** * @medium */ final class PhptTestCaseTest extends TestCase { private const EXPECT_CONTENT = << --EXPECT-- Hello PHPUnit! EOF; private const EXPECTF_CONTENT = << --EXPECTF-- Hello %s! EOF; private const EXPECTREGEX_CONTENT = << --EXPECTREGEX-- Hello [HPU]{4}[nit]{3}! EOF; private const FILE_SECTION = << EOF; /** * @var string */ private $dirname; /** * @var string */ private $filename; /** * @var PhptTestCase */ private $testCase; /** * @var AbstractPhpProcess|\PHPUnit\Framework\MockObject\MockObject */ private $phpProcess; protected function setUp(): void { $this->dirname = \sys_get_temp_dir(); $this->filename = $this->dirname . '/phpunit.phpt'; \touch($this->filename); $this->phpProcess = $this->getMockForAbstractClass(AbstractPhpProcess::class, [], '', false); $this->testCase = new PhptTestCase($this->filename, $this->phpProcess); } protected function tearDown(): void { @\unlink($this->filename); $this->phpProcess = null; $this->testCase = null; } public function testAlwaysReportsNumberOfAssertionsIsOne(): void { $this->assertSame(1, $this->testCase->getNumAssertions()); } public function testAlwaysReportsItDoesNotUseADataprovider(): void { $this->assertSame(false, $this->testCase->usesDataProvider()); } public function testShouldRunFileSectionAsTest(): void { $this->setPhpContent($this->ensureCorrectEndOfLine(self::EXPECT_CONTENT)); $fileSection = '' . \PHP_EOL; $this->phpProcess ->expects($this->once()) ->method('runJob') ->with($fileSection) ->will($this->returnValue(['stdout' => '', 'stderr' => ''])); $this->testCase->run(); } public function testRenderFileSection(): void { $this->setPhpContent($this->ensureCorrectEndOfLine( << --EXPECT-- Something EOF )); $renderedCode = "dirname . "' . '" . $this->filename . "'; ?>" . \PHP_EOL; $this->phpProcess ->expects($this->once()) ->method('runJob') ->with($renderedCode) ->will($this->returnValue(['stdout' => '', 'stderr' => ''])); $this->testCase->run(); } public function testRenderSkipifSection(): void { $phptContent = self::EXPECT_CONTENT . \PHP_EOL; $phptContent .= '--SKIPIF--' . \PHP_EOL; $phptContent .= "" . \PHP_EOL; $this->setPhpContent($phptContent); $renderedCode = "filename . "'; ?>" . \PHP_EOL; $this->phpProcess ->expects($this->at(0)) ->method('runJob') ->with($renderedCode) ->will($this->returnValue(['stdout' => '', 'stderr' => ''])); $this->testCase->run(); } public function testShouldRunSkipifSectionWhenExists(): void { $skipifSection = '' . \PHP_EOL; $phptContent = self::EXPECT_CONTENT . \PHP_EOL; $phptContent .= '--SKIPIF--' . \PHP_EOL; $phptContent .= $skipifSection; $this->setPhpContent($phptContent); $this->phpProcess ->expects($this->at(0)) ->method('runJob') ->with($skipifSection) ->will($this->returnValue(['stdout' => '', 'stderr' => ''])); $this->testCase->run(); } public function testShouldNotRunTestSectionIfSkipifSectionReturnsOutputWithSkipWord(): void { $skipifSection = '' . \PHP_EOL; $phptContent = self::EXPECT_CONTENT . \PHP_EOL; $phptContent .= '--SKIPIF--' . \PHP_EOL; $phptContent .= $skipifSection; $this->setPhpContent($phptContent); $this->phpProcess ->expects($this->once()) ->method('runJob') ->with($skipifSection) ->will($this->returnValue(['stdout' => 'skip: Reason', 'stderr' => ''])); $this->testCase->run(); } public function testShouldRunCleanSectionWhenDefined(): void { $cleanSection = '' . \PHP_EOL; $phptContent = self::EXPECT_CONTENT . \PHP_EOL; $phptContent .= '--CLEAN--' . \PHP_EOL; $phptContent .= $cleanSection; $this->setPhpContent($phptContent); $this->phpProcess ->expects($this->at(1)) ->method('runJob') ->with($cleanSection); $this->testCase->run(); } public function testShouldSkipTestWhenPhptFileIsEmpty(): void { $this->setPhpContent(''); $result = $this->testCase->run(); $this->assertCount(1, $result->skipped()); $this->assertSame('Invalid PHPT file', $result->skipped()[0]->thrownException()->getMessage()); } public function testShouldSkipTestWhenFileSectionIsMissing(): void { $this->setPhpContent( <<testCase->run(); $this->assertCount(1, $result->skipped()); $this->assertSame('Invalid PHPT file', $result->skipped()[0]->thrownException()->getMessage()); } public function testShouldSkipTestWhenThereIsNoExpecOrExpectifOrExpecregexSectionInPhptFile(): void { $this->setPhpContent( << EOF ); $result = $this->testCase->run(); $this->assertCount(1, $result->skipped()); $skipMessage = $result->skipped()[0]->thrownException()->getMessage(); $this->assertSame('Invalid PHPT file', $skipMessage); } public function testShouldSkipTestWhenSectionHeaderIsMalformed(): void { $this->setPhpContent( <<testCase->run(); $this->assertCount(1, $result->skipped()); $skipMessage = $result->skipped()[0]->thrownException()->getMessage(); $this->assertSame('Invalid PHPT file: empty section header', $skipMessage); } public function testShouldValidateExpectSession(): void { $this->setPhpContent(self::EXPECT_CONTENT); $this->phpProcess ->expects($this->once()) ->method('runJob') ->with(self::FILE_SECTION) ->will($this->returnValue(['stdout' => 'Hello PHPUnit!', 'stderr' => ''])); $result = $this->testCase->run(); $this->assertTrue($result->wasSuccessful()); } public function testShouldValidateExpectfSession(): void { $this->setPhpContent(self::EXPECTF_CONTENT); $this->phpProcess ->expects($this->once()) ->method('runJob') ->with(self::FILE_SECTION) ->will($this->returnValue(['stdout' => 'Hello PHPUnit!', 'stderr' => ''])); $result = $this->testCase->run(); $this->assertTrue($result->wasSuccessful()); } public function testShouldValidateExpectregexSession(): void { $this->setPhpContent(self::EXPECTREGEX_CONTENT); $this->phpProcess ->expects($this->once()) ->method('runJob') ->with(self::FILE_SECTION) ->will($this->returnValue(['stdout' => 'Hello PHPUnit!', 'stderr' => ''])); $result = $this->testCase->run(); $this->assertTrue($result->wasSuccessful()); } /** * Defines the content of the current PHPT test. * * @param string $content */ private function setPhpContent($content): void { \file_put_contents($this->filename, $content); } /** * Ensures the correct line ending is used for comparison * * @param string $content * * @return string */ private function ensureCorrectEndOfLine($content) { return \strtr( $content, [ "\r\n" => \PHP_EOL, "\r" => \PHP_EOL, "\n" => \PHP_EOL, ] ); } } PK!z}%Runner/DefaultTestResultCacheTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Runner; use PHPUnit\Framework\TestCase; /** * @covers \PHPUnit\Runner\DefaultTestResultCache * @small */ final class DefaultTestResultCacheTest extends TestCase { /** * @var DefaultTestResultCache */ private $subject; protected function setUp(): void { $this->subject = new DefaultTestResultCache(); } public function testGetTimeForNonExistentTestNameReturnsFloatZero(): void { $this->assertSame(0.0, $this->subject->getTime('doesNotExist')); } } PK!#Runner/ResultCacheExtensionTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Runner; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCaseTest; use PHPUnit\Framework\TestResult; use PHPUnit\Framework\TestSuite; /** * @group test-reorder * @small */ final class ResultCacheExtensionTest extends TestCase { /** * @var DefaultTestResultCache */ protected $cache; /** * @var ResultCacheExtension */ protected $extension; /** * @var TestResult */ protected $result; protected function setUp(): void { $this->cache = new DefaultTestResultCache; $this->extension = new ResultCacheExtension($this->cache); $listener = new TestListenerAdapter; $listener->add($this->extension); $this->result = new TestResult; $this->result->addListener($listener); } /** * @testdox Clean up test name $_dataName * @dataProvider longTestNamesDataprovider */ public function testStripsDataproviderParametersFromTestName(string $testName, string $expectedTestName): void { $test = new TestCaseTest($testName); $test->run($this->result); $this->assertSame(BaseTestRunner::STATUS_ERROR, $this->cache->getState($expectedTestName)); } public function longTestNamesDataprovider(): array { return [ 'ClassName::testMethod' => [ 'testSomething', TestCaseTest::class . '::testSomething', ], 'ClassName::testMethod and data set number and vardump' => [ 'testMethod with data set #123 (\'a\', "A", 0, false)', TestCaseTest::class . '::testMethod with data set #123', ], 'ClassName::testMethod and data set name and vardump' => [ 'testMethod with data set "data name" (\'a\', "A\", 0, false)', TestCaseTest::class . '::testMethod with data set "data name"', ], ]; } public function testError(): void { $test = new \TestError('test_name'); $test->run($this->result); $this->assertSame(BaseTestRunner::STATUS_ERROR, $this->cache->getState(\TestError::class . '::test_name')); } public function testFailure(): void { $test = new \Failure('test_name'); $test->run($this->result); $this->assertSame(BaseTestRunner::STATUS_FAILURE, $this->cache->getState(\Failure::class . '::test_name')); } public function testSkipped(): void { $test = new \TestSkipped('test_name'); $test->run($this->result); $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $this->cache->getState(\TestSkipped::class . '::test_name')); } public function testIncomplete(): void { $test = new \TestIncomplete('test_name'); $test->run($this->result); $this->assertSame(BaseTestRunner::STATUS_INCOMPLETE, $this->cache->getState(\TestIncomplete::class . '::test_name')); } public function testPassedTestsOnlyCacheTime(): void { $test = new \Success('test_name'); $test->run($this->result); $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $this->cache->getState(\Success::class . '::test_name')); } public function testWarning(): void { $test = new \TestWarning('test_name'); $test->run($this->result); $this->assertSame(BaseTestRunner::STATUS_WARNING, $this->cache->getState(\TestWarning::class . '::test_name')); } public function testRisky(): void { $test = new \TestRisky('test_name'); $test->run($this->result); $this->assertSame(BaseTestRunner::STATUS_RISKY, $this->cache->getState(\TestRisky::class . '::test_name')); } public function testEmptySuite(): void { $suite = new TestSuite; $suite->addTestSuite(\EmptyTestCaseTest::class); $suite->run($this->result); $this->assertSame(BaseTestRunner::STATUS_WARNING, $this->cache->getState('Warning')); } } PK!IeBBRunner/TestResultCacheTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use PHPUnit\Framework\TestCase; use PHPUnit\Runner\BaseTestRunner; use PHPUnit\Runner\DefaultTestResultCache; /** * @group test-reorder * @small */ final class TestResultCacheTest extends TestCase { public function testReadsCacheFromProvidedFilename(): void { $cacheFile = TEST_FILES_PATH . '../end-to-end/execution-order/_files/MultiDependencyTest_result_cache.txt'; $cache = new DefaultTestResultCache($cacheFile); $cache->load(); $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $cache->getState(\MultiDependencyTest::class . '::testOne')); $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $cache->getState(\MultiDependencyTest::class . '::testFive')); } public function testDoesClearCacheBeforeLoad(): void { $cacheFile = TEST_FILES_PATH . '../end-to-end/execution-order/_files/MultiDependencyTest_result_cache.txt'; $cache = new DefaultTestResultCache($cacheFile); $cache->setState('someTest', BaseTestRunner::STATUS_FAILURE); $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $cache->getState(\MultiDependencyTest::class . '::testFive')); $cache->load(); $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $cache->getState(\MultiDependencyTest::class . '::someTest')); $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $cache->getState(\MultiDependencyTest::class . '::testFive')); } public function testShouldNotSerializePassedTestsAsDefectButTimeIsStored(): void { $cache = new DefaultTestResultCache; $cache->setState('testOne', BaseTestRunner::STATUS_PASSED); $cache->setTime('testOne', 123); $data = \serialize($cache); $this->assertSame('C:37:"PHPUnit\Runner\DefaultTestResultCache":64:{a:2:{s:7:"defects";a:0:{}s:5:"times";a:1:{s:7:"testOne";d:123;}}}', $data); } public function testCanPersistCacheToFile(): void { // Create a cache with one result and store it $cacheFile = \tempnam(\sys_get_temp_dir(), 'phpunit_'); $cache = new DefaultTestResultCache($cacheFile); $testName = 'test' . \uniqid(); $cache->setState($testName, BaseTestRunner::STATUS_SKIPPED); $cache->persist(); unset($cache); // Load the cache we just created $loadedCache = new DefaultTestResultCache($cacheFile); $loadedCache->load(); $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $loadedCache->getState($testName)); // Clean up \unlink($cacheFile); } public function testShouldReturnEmptyCacheWhenFileDoesNotExist(): void { $cache = new DefaultTestResultCache('/a/wrong/path/file'); $cache->load(); $this->assertTrue($this->isSerializedEmptyCache(\serialize($cache))); } public function testShouldReturnEmptyCacheFromInvalidFile(): void { $cacheFile = \tempnam(\sys_get_temp_dir(), 'phpunit_'); \file_put_contents($cacheFile, ''); $cache = new DefaultTestResultCache($cacheFile); $cache->load(); $this->assertTrue($this->isSerializedEmptyCache(\serialize($cache))); } public function isSerializedEmptyCache(string $data): bool { return $data === 'C:37:"PHPUnit\Runner\DefaultTestResultCache":44:{a:2:{s:7:"defects";a:0:{}s:5:"times";a:0:{}}}'; } } PK! IjjRunner/TestSuiteSorterTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Runner; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestSuite; /** * @testdox Reordering test execution * @group test-reorder * @small */ final class TestSuiteSorterTest extends TestCase { /** * Constants to improve clarity of @dataprovider */ private const IGNORE_DEPENDENCIES = false; private const RESOLVE_DEPENDENCIES = true; private const MULTIDEPENDENCYTEST_EXECUTION_ORDER = [ \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', ]; public function testThrowsExceptionWhenUsingInvalidOrderOption(): void { $suite = new TestSuite; $suite->addTestSuite(\MultiDependencyTest::class); $sorter = new TestSuiteSorter; $this->expectException(Exception::class); $this->expectExceptionMessage('$order must be one of TestSuiteSorter::ORDER_[DEFAULT|REVERSED|RANDOMIZED|DURATION|SIZE]'); $sorter->reorderTestsInSuite($suite, -1, false, TestSuiteSorter::ORDER_DEFAULT); } public function testThrowsExceptionWhenUsingInvalidOrderDefectsOption(): void { $suite = new TestSuite; $suite->addTestSuite(\MultiDependencyTest::class); $sorter = new TestSuiteSorter; $this->expectException(Exception::class); $this->expectExceptionMessage('$orderDefects must be one of TestSuiteSorter::ORDER_DEFAULT, TestSuiteSorter::ORDER_DEFECTS_FIRST'); $sorter->reorderTestsInSuite($suite, TestSuiteSorter::ORDER_DEFAULT, false, -1); } /** * @testdox Empty TestSuite not affected (order=$order, resolve=$resolveDependencies, defects=$orderDefects) * @dataProvider suiteSorterOptionPermutationsProvider */ public function testShouldNotAffectEmptyTestSuite(int $order, bool $resolveDependencies, int $orderDefects): void { $sorter = new TestSuiteSorter; $suite = new TestSuite; $sorter->reorderTestsInSuite($suite, $order, $resolveDependencies, $orderDefects); $this->assertEmpty($suite->tests()); $this->assertEmpty($sorter->getOriginalExecutionOrder()); $this->assertEmpty($sorter->getExecutionOrder()); } /** * @dataProvider commonSorterOptionsProvider */ public function testBasicExecutionOrderOptions(int $order, bool $resolveDependencies, array $expectedOrder): void { $suite = new TestSuite; $suite->addTestSuite(\MultiDependencyTest::class); $sorter = new TestSuiteSorter; $sorter->reorderTestsInSuite($suite, $order, $resolveDependencies, TestSuiteSorter::ORDER_DEFAULT); $this->assertSame(self::MULTIDEPENDENCYTEST_EXECUTION_ORDER, $sorter->getOriginalExecutionOrder()); $this->assertSame($expectedOrder, $sorter->getExecutionOrder()); } public function testCanSetRandomizationWithASeed(): void { $suite = new TestSuite; $suite->addTestSuite(\MultiDependencyTest::class); $sorter = new TestSuiteSorter; \mt_srand(54321); $sorter->reorderTestsInSuite($suite, TestSuiteSorter::ORDER_RANDOMIZED, false, TestSuiteSorter::ORDER_DEFAULT); $expectedOrder = [ \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testOne', ]; $this->assertSame($expectedOrder, $sorter->getExecutionOrder()); } public function testCanSetRandomizationWithASeedAndResolveDependencies(): void { $suite = new TestSuite; $suite->addTestSuite(\MultiDependencyTest::class); $sorter = new TestSuiteSorter; \mt_srand(54321); $sorter->reorderTestsInSuite($suite, TestSuiteSorter::ORDER_RANDOMIZED, true, TestSuiteSorter::ORDER_DEFAULT); $expectedOrder = [ \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', ]; $this->assertSame($expectedOrder, $sorter->getExecutionOrder()); } /** * @dataProvider orderDurationWithoutCacheProvider */ public function testOrderDurationWithoutCache(bool $resolveDependencies, array $expected): void { $suite = new TestSuite; $suite->addTestSuite(\MultiDependencyTest::class); $sorter = new TestSuiteSorter; $sorter->reorderTestsInSuite( $suite, TestSuiteSorter::ORDER_DURATION, $resolveDependencies, TestSuiteSorter::ORDER_DEFAULT ); $this->assertSame($expected, $sorter->getExecutionOrder()); } public function orderDurationWithoutCacheProvider(): array { return [ 'dependency-ignore' => [ self::IGNORE_DEPENDENCIES, [ \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', ], ], 'dependency-resolve' => [ self::RESOLVE_DEPENDENCIES, [ \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', ], ], ]; } /** * @dataProvider orderDurationWithCacheProvider */ public function testOrderDurationWithCache(bool $resolveDependencies, array $testTimes, array $expected): void { $suite = new TestSuite; $suite->addTestSuite(\MultiDependencyTest::class); $cache = new DefaultTestResultCache; foreach ($testTimes as $testName => $time) { $cache->setTime(\MultiDependencyTest::class . '::' . $testName, $time); } $sorter = new TestSuiteSorter($cache); $sorter->reorderTestsInSuite( $suite, TestSuiteSorter::ORDER_DURATION, $resolveDependencies, TestSuiteSorter::ORDER_DEFAULT ); $this->assertSame($expected, $sorter->getExecutionOrder()); } public function orderDurationWithCacheProvider(): array { return [ 'duration-same-dependency-ignore' => [ self::IGNORE_DEPENDENCIES, [ 'testOne' => 1, 'testTwo' => 1, 'testThree' => 1, 'testFour' => 1, 'testFive' => 1, ], [ \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', ], ], 'duration-same-dependency-resolve' => [ self::RESOLVE_DEPENDENCIES, [ 'testOne' => 1, 'testTwo' => 1, 'testThree' => 1, 'testFour' => 1, 'testFive' => 1, ], [ \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', ], ], 'duration-different-dependency-ignore' => [ self::IGNORE_DEPENDENCIES, [ 'testOne' => 5, 'testTwo' => 3, 'testThree' => 4, 'testFour' => 1, 'testFive' => 2, ], [ \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testOne', ], ], 'duration-different-dependency-resolve' => [ self::RESOLVE_DEPENDENCIES, [ 'testOne' => 5, 'testTwo' => 3, 'testThree' => 4, 'testFour' => 1, 'testFive' => 2, ], [ \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', ], ], ]; } /** * @dataProvider defectsSorterOptionsProvider */ public function testSuiteSorterDefectsOptions(int $order, bool $resolveDependencies, array $runState, array $expected): void { $suite = new TestSuite; $suite->addTestSuite(\MultiDependencyTest::class); $cache = new DefaultTestResultCache; foreach ($runState as $testName => $data) { $cache->setState(\MultiDependencyTest::class . '::' . $testName, $data['state']); $cache->setTime(\MultiDependencyTest::class . '::' . $testName, $data['time']); } $sorter = new TestSuiteSorter($cache); $sorter->reorderTestsInSuite($suite, $order, $resolveDependencies, TestSuiteSorter::ORDER_DEFECTS_FIRST); $this->assertSame($expected, $sorter->getExecutionOrder()); } /** * A @dataprovider for basic execution reordering options based on MultiDependencyTest * This class has the following relevant properties: * - it has five tests 'testOne' ... 'testFive' * - 'testThree' @depends on both 'testOne' and 'testTwo' * - 'testFour' @depends on 'MultiDependencyTest::testThree' to test FQN @depends * - 'testFive' has no dependencies */ public function commonSorterOptionsProvider(): array { return [ 'default' => [ TestSuiteSorter::ORDER_DEFAULT, self::IGNORE_DEPENDENCIES, [ \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', ], ], // Activating dependency resolution should have no effect under normal circumstances 'resolve default' => [ TestSuiteSorter::ORDER_DEFAULT, self::RESOLVE_DEPENDENCIES, [ \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', ], ], // Reversing without checks should give a simple reverse order 'reverse' => [ TestSuiteSorter::ORDER_REVERSED, self::IGNORE_DEPENDENCIES, [ \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testOne', ], ], // Reversing with resolution still allows testFive to move to front, testTwo before testOne 'resolve reverse' => [ TestSuiteSorter::ORDER_REVERSED, self::RESOLVE_DEPENDENCIES, [ \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', ], ], ]; } /** * A @dataprovider for testing defects execution reordering options based on MultiDependencyTest * This class has the following relevant properties: * - it has five tests 'testOne' ... 'testFive' * - 'testThree' @depends on both 'testOne' and 'testTwo' * - 'testFour' @depends on 'MultiDependencyTest::testThree' to test FQN @depends * - 'testFive' has no dependencies */ public function defectsSorterOptionsProvider(): array { return [ // The most simple situation should work as normal 'default, no defects' => [ TestSuiteSorter::ORDER_DEFAULT, self::IGNORE_DEPENDENCIES, [ 'testOne' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testTwo' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testThree' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testFour' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testFive' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], ], [ \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', ], ], // Running with an empty cache should not spook the TestSuiteSorter 'default, empty result cache' => [ TestSuiteSorter::ORDER_DEFAULT, self::IGNORE_DEPENDENCIES, [ // empty result cache ], [ \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', ], ], // testFive is independent and can be moved to the front 'default, testFive skipped' => [ TestSuiteSorter::ORDER_DEFAULT, self::IGNORE_DEPENDENCIES, [ 'testOne' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testTwo' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testThree' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testFour' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testFive' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 1], ], [ \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', ], ], // Defects in testFive and testTwo, but the faster testFive should be run first 'default, testTwo testFive skipped' => [ TestSuiteSorter::ORDER_DEFAULT, self::IGNORE_DEPENDENCIES, [ 'testOne' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testTwo' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 1], 'testThree' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testFour' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testFive' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 0], ], [ \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', ], ], // Skipping testThree will move it to the front when ignoring dependencies 'default, testThree skipped' => [ TestSuiteSorter::ORDER_DEFAULT, self::IGNORE_DEPENDENCIES, [ 'testOne' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testTwo' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testThree' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 1], 'testFour' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testFive' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], ], [ \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', ], ], // Skipping testThree will move it to the front but behind its dependencies 'default resolve, testThree skipped' => [ TestSuiteSorter::ORDER_DEFAULT, self::RESOLVE_DEPENDENCIES, [ 'testOne' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testTwo' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testThree' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 1], 'testFour' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testFive' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], ], [ \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testFive', ], ], // Skipping testThree will move it to the front and keep the others reversed 'reverse, testThree skipped' => [ TestSuiteSorter::ORDER_REVERSED, self::IGNORE_DEPENDENCIES, [ 'testOne' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testTwo' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testThree' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 1], 'testFour' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testFive' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], ], [ \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testFour', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testOne', ], ], // Demonstrate a limit of the dependency resolver: after sorting defects to the front, // the resolver will mark testFive done before testThree because of dependencies 'default resolve, testThree skipped, testFive fast' => [ TestSuiteSorter::ORDER_DEFAULT, self::RESOLVE_DEPENDENCIES, [ 'testOne' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testTwo' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testThree' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 0], 'testFour' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testFive' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 1], ], [ \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', ], ], // Torture test // - incomplete TestResultCache // - skipped testThree: will move it to the front as far as possible // - testOne and testTwo are required before testThree, but can be reversed locally // - testFive is independent will remain reversed up front 'reverse resolve, testThree skipped' => [ TestSuiteSorter::ORDER_REVERSED, self::RESOLVE_DEPENDENCIES, [ 'testOne' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testTwo' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testThree' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 1], ], [ \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', ], ], // Make sure the dependency resolver is not confused by failing tests. // Scenario: Four has a @depends on Three and fails. Result: Three is still run first // testFive also fails but can be moved around freely and will be up front. 'depends first, then defects' => [ TestSuiteSorter::ORDER_DEFAULT, self::RESOLVE_DEPENDENCIES, [ 'testOne' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testTwo' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testThree' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], 'testFour' => ['state' => BaseTestRunner::STATUS_FAILURE, 'time' => 1], 'testFive' => ['state' => BaseTestRunner::STATUS_FAILURE, 'time' => 1], ], [ \MultiDependencyTest::class . '::testFive', \MultiDependencyTest::class . '::testOne', \MultiDependencyTest::class . '::testTwo', \MultiDependencyTest::class . '::testThree', \MultiDependencyTest::class . '::testFour', ], ], ]; } /** * @see https://github.com/lstrojny/phpunit-clever-and-smart/issues/38 */ public function testCanHandleSuiteWithEmptyTestCase(): void { $suite = new TestSuite; $suite->addTestSuite(\EmptyTestCaseTest::class); $sorter = new TestSuiteSorter; $sorter->reorderTestsInSuite($suite, TestSuiteSorter::ORDER_DEFAULT, false, TestSuiteSorter::ORDER_DEFAULT); $this->assertSame(\EmptyTestCaseTest::class, $suite->tests()[0]->getName()); $this->assertSame('No tests found in class "EmptyTestCaseTest".', $suite->tests()[0]->tests()[0]->getMessage()); } public function suiteSorterOptionPermutationsProvider(): array { $orderValues = [TestSuiteSorter::ORDER_DEFAULT, TestSuiteSorter::ORDER_REVERSED, TestSuiteSorter::ORDER_RANDOMIZED]; $resolveValues = [false, true]; $orderDefectsValues = [TestSuiteSorter::ORDER_DEFAULT, TestSuiteSorter::ORDER_DEFECTS_FIRST]; $data = []; foreach ($orderValues as $order) { foreach ($resolveValues as $resolve) { foreach ($orderDefectsValues as $orderDefects) { $data[] = [$order, $resolve, $orderDefects]; } } } return $data; } public function testOrderBySize(): void { $suite = new TestSuite; $suite->addTestSuite(\TestWithDifferentSizes::class); $sorter = new TestSuiteSorter; $sorter->reorderTestsInSuite($suite, TestSuiteSorter::ORDER_SIZE, true, TestSuiteSorter::ORDER_DEFAULT); $expectedOrder = [ \TestWithDifferentSizes::class . '::testWithSizeSmall', \TestWithDifferentSizes::class . '::testDataProviderWithSizeSmall with data set #0', \TestWithDifferentSizes::class . '::testDataProviderWithSizeSmall with data set #1', \TestWithDifferentSizes::class . '::testDataProviderWithSizeMedium with data set #0', \TestWithDifferentSizes::class . '::testDataProviderWithSizeMedium with data set #1', \TestWithDifferentSizes::class . '::testWithSizeMedium', \TestWithDifferentSizes::class . '::testWithSizeLarge', \TestWithDifferentSizes::class . '::testWithSizeUnknown', ]; $this->assertSame($expectedOrder, $sorter->getExecutionOrder()); } } PK!"  (Runner/Filter/NameFilterIteratorTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Runner\Filter; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestSuite; /** * @small */ final class NameFilterIteratorTest extends TestCase { public function testCaseSensitiveMatch(): void { $this->assertTrue($this->createFilter('BankAccountTest')->accept()); } public function testCaseInsensitiveMatch(): void { $this->assertTrue($this->createFilter('bankaccounttest')->accept()); } private function createFilter(string $filter): NameFilterIterator { $suite = new TestSuite; $suite->addTest(new \BankAccountTest('testBalanceIsInitiallyZero')); $iterator = new NameFilterIterator($suite->getIterator(), $filter); $iterator->rewind(); return $iterator; } } PK!H..!Framework/SkippedTestCaseTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use PHPUnit\Runner\BaseTestRunner; final class SkippedTestCaseTest extends TestCase { public function testDefaults(): void { $testCase = new SkippedTestCase( 'Foo', 'testThatBars' ); $this->assertSame('', $testCase->getMessage()); } public function testGetNameReturnsClassAndMethodName(): void { $className = 'Foo'; $methodName = 'testThatBars'; $testCase = new SkippedTestCase( $className, $methodName ); $name = \sprintf( '%s::%s', $className, $methodName ); $this->assertSame($name, $testCase->getName()); } public function testGetMessageReturnsMessage(): void { $message = 'Somehow skipped, right?'; $testCase = new SkippedTestCase( 'Foo', 'testThatBars', $message ); $this->assertSame($message, $testCase->getMessage()); } public function testRunMarksTestAsSkipped(): void { $className = 'Foo'; $methodName = 'testThatBars'; $message = 'Somehow skipped, right?'; $testCase = new SkippedTestCase( $className, $methodName, $message ); $result = $testCase->run(); $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $testCase->getStatus()); $this->assertSame(1, $result->skippedCount()); $failures = $result->skipped(); $failure = \array_shift($failures); $name = \sprintf( '%s::%s', $className, $methodName ); $this->assertSame($name, $failure->getTestName()); $this->assertSame($message, $failure->exceptionMessage()); } } PK!WW$Framework/IncompleteTestCaseTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use PHPUnit\Runner\BaseTestRunner; final class IncompleteTestCaseTest extends TestCase { public function testDefaults(): void { $testCase = new IncompleteTestCase( 'Foo', 'testThatBars' ); $this->assertSame('', $testCase->getMessage()); } public function testGetNameReturnsClassAndMethodName(): void { $className = 'Foo'; $methodName = 'testThatBars'; $testCase = new IncompleteTestCase( $className, $methodName ); $name = \sprintf( '%s::%s', $className, $methodName ); $this->assertSame($name, $testCase->getName()); } public function testGetMessageReturnsMessage(): void { $message = 'Somehow incomplete, right?'; $testCase = new IncompleteTestCase( 'Foo', 'testThatBars', $message ); $this->assertSame($message, $testCase->getMessage()); } public function testRunMarksTestAsIncomplete(): void { $className = 'Foo'; $methodName = 'testThatBars'; $message = 'Somehow incomplete, right?'; $testCase = new IncompleteTestCase( $className, $methodName, $message ); $result = $testCase->run(); $this->assertSame(BaseTestRunner::STATUS_INCOMPLETE, $testCase->getStatus()); $this->assertSame(1, $result->notImplementedCount()); $failures = $result->notImplemented(); $failure = \array_shift($failures); $name = \sprintf( '%s::%s', $className, $methodName ); $this->assertSame($name, $failure->getTestName()); $this->assertSame($message, $failure->exceptionMessage()); } } PK!!og#Framework/Constraint/IsJsonTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class IsJsonTest extends ConstraintTestCase { public static function evaluateDataprovider(): array { return [ 'valid JSON' => [true, '{}'], 'empty string should be treated as invalid JSON' => [false, ''], ]; } /** * @testdox Evaluate $_dataName * @dataProvider evaluateDataprovider * * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testEvaluate($expected, $jsonOther): void { $constraint = new IsJson; $this->assertEquals($expected, $constraint->evaluate($jsonOther, '', true)); } public function testIsJsonCanBeExportedAsString(): void { $isJson = new IsJson; $this->assertSame('is valid JSON', $isJson->toString()); } public function testIsJsonCanBeEmptyString(): void { $isJson = new IsJson; try { $isJson->evaluate(''); } catch (ExpectationFailedException $e) { $this->assertEquals( << * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class ClassHasAttributeTest extends ConstraintTestCase { public function testConstraintClassHasAttribute(): void { $constraint = new ClassHasAttribute( 'privateAttribute' ); $this->assertTrue($constraint->evaluate(\ClassWithNonPublicAttributes::class, '', true)); $this->assertFalse($constraint->evaluate(\stdClass::class, '', true)); $this->assertEquals('has attribute "privateAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(\stdClass::class); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintClassHasAttribute2(): void { $constraint = new ClassHasAttribute( 'privateAttribute' ); try { $constraint->evaluate(\stdClass::class, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!{z##$Framework/Constraint/IsEmptyTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class IsEmptyTest extends ConstraintTestCase { public function testConstraintIsEmpty(): void { $constraint = new IsEmpty; $this->assertFalse($constraint->evaluate(['foo'], '', true)); $this->assertTrue($constraint->evaluate([], '', true)); $this->assertFalse($constraint->evaluate(new \ArrayObject(['foo']), '', true)); $this->assertTrue($constraint->evaluate(new \ArrayObject([]), '', true)); $this->assertEquals('is empty', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(['foo']); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsEmpty2(): void { $constraint = new IsEmpty; try { $constraint->evaluate(['foo'], 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } /** * @ticket https://github.com/sebastianbergmann/phpunit/issues/3743 */ public function test_EmptyIterator_is_handled_correctly(): void { $constraint = new IsEmpty; $this->assertTrue($constraint->evaluate(new \EmptyIterator, '', true)); } } PK!A9k'''Framework/Constraint/FileExistsTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class FileExistsTest extends ConstraintTestCase { public function testConstraintFileExists(): void { $constraint = new FileExists; $this->assertFalse($constraint->evaluate('foo', '', true)); $this->assertEquals('file exists', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate('foo'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintFileExists2(): void { $constraint = new FileExists; try { $constraint->evaluate('foo', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!EiAA'Framework/Constraint/IsWritableTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class IsWritableTest extends ConstraintTestCase { public function testConstraintIsWritable(): void { $constraint = new IsWritable; $this->assertFalse($constraint->evaluate('foo', '', true)); $this->assertEquals('is writable', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate('foo'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!\@+Framework/Constraint/ConstraintTestCase.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\SelfDescribing; use PHPUnit\Framework\TestCase; /** * @small */ abstract class ConstraintTestCase extends TestCase { final public function testIsCountable(): void { $className = $this->className(); $reflection = new \ReflectionClass($className); $this->assertTrue($reflection->implementsInterface(\Countable::class), \sprintf( 'Failed to assert that "%s" implements "%s".', $className, \Countable::class )); } final public function testIsSelfDescribing(): void { $className = $this->className(); $reflection = new \ReflectionClass($className); $this->assertTrue($reflection->implementsInterface(SelfDescribing::class), \sprintf( 'Failed to assert that "%s" implements "%s".', $className, SelfDescribing::class )); } /** * Returns the class name of the constraint. */ final protected function className(): string { return \preg_replace( '/Test$/', '', static::class ); } } PK!kZ <Framework/Constraint/JsonMatchesErrorMessageProviderTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\TestCase; /** * @small */ final class JsonMatchesErrorMessageProviderTest extends TestCase { public static function determineJsonErrorDataprovider(): array { return [ 'JSON_ERROR_NONE' => [ null, 'json_error_none', '', ], 'JSON_ERROR_DEPTH' => [ 'Maximum stack depth exceeded', \JSON_ERROR_DEPTH, '', ], 'prefixed JSON_ERROR_DEPTH' => [ 'TUX: Maximum stack depth exceeded', \JSON_ERROR_DEPTH, 'TUX: ', ], 'JSON_ERROR_STATE_MISMatch' => [ 'Underflow or the modes mismatch', \JSON_ERROR_STATE_MISMATCH, '', ], 'JSON_ERROR_CTRL_CHAR' => [ 'Unexpected control character found', \JSON_ERROR_CTRL_CHAR, '', ], 'JSON_ERROR_SYNTAX' => [ 'Syntax error, malformed JSON', \JSON_ERROR_SYNTAX, '', ], 'JSON_ERROR_UTF8`' => [ 'Malformed UTF-8 characters, possibly incorrectly encoded', \JSON_ERROR_UTF8, '', ], 'Invalid error indicator' => [ 'Unknown error', 55, '', ], ]; } public static function translateTypeToPrefixDataprovider(): array { return [ 'expected' => ['Expected value JSON decode error - ', 'expected'], 'actual' => ['Actual value JSON decode error - ', 'actual'], 'default' => ['', ''], ]; } /** * @dataProvider translateTypeToPrefixDataprovider * * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testTranslateTypeToPrefix($expected, $type): void { $this->assertEquals( $expected, JsonMatchesErrorMessageProvider::translateTypeToPrefix($type) ); } /** * @testdox Determine JSON error $_dataName * @dataProvider determineJsonErrorDataprovider * * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testDetermineJsonError($expected, $error, $prefix): void { $this->assertEquals( $expected, JsonMatchesErrorMessageProvider::determineJsonError( (string) $error, $prefix ) ); } } PK!&Framework/Constraint/LogicalOrTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class LogicalOrTest extends ConstraintTestCase { public function testSetConstraintsDecoratesNonConstraintWithIsEqual(): void { $constraints = [ new \stdClass, ]; $constraint = new LogicalOr; $constraint->setConstraints($constraints); $this->assertTrue($constraint->evaluate(new \stdClass, '', true)); } public function testCountReturnsCountOfComposedConstraints(): void { $counts = [ 3, 5, 8, ]; $constraints = \array_map(function (int $count) { return \CountConstraint::fromCount($count); }, $counts); $constraint = new LogicalOr; $constraint->setConstraints($constraints); $expected = \array_sum($counts); $this->assertSame($expected, $constraint->count()); } public function testToStringReturnsImplodedStringRepresentationOfComposedConstraintsGluedWithOr(): void { $names = [ 'is healthy', 'is rich in amino acids', 'is rich in unsaturated fats', ]; $constraints = \array_map(function (string $name) { return \NamedConstraint::fromName($name); }, $names); $constraint = new LogicalOr; $constraint->setConstraints($constraints); $expected = \implode(' or ', $names); $this->assertSame($expected, $constraint->toString()); } /** * @dataProvider providerFailingConstraints * * @param Constraint[] $constraints */ public function testEvaluateReturnsFalseIfAllOfTheComposedConstraintsEvaluateToFalse(array $constraints): void { $constraint = new LogicalOr; $constraint->setConstraints($constraints); $this->assertFalse($constraint->evaluate('whatever', '', true)); } /** * @dataProvider providerSucceedingConstraints * * @param Constraint[] $constraints */ public function testEvaluateReturnsTrueIfAnyOfTheComposedConstraintsEvaluateToTrue(array $constraints): void { $constraint = LogicalOr::fromConstraints(...$constraints); $this->assertTrue($constraint->evaluate('whatever', '', true)); } /** * @dataProvider providerFailingConstraints * * @param Constraint[] $constraints */ public function testEvaluateThrowsExceptionIfAllOfTheComposedConstraintsEvaluateToFalse(array $constraints): void { $other = 'whatever'; $constraint = new LogicalOr; $constraint->setConstraints($constraints); try { $constraint->evaluate($other); } catch (ExpectationFailedException $exception) { $toString = $this->stringify($constraints); $expectedDescription = <<assertEquals($expectedDescription, TestFailure::exceptionToString($exception)); return; } $this->fail(); } /** * @dataProvider providerFailingConstraints * * @param Constraint[] $constraints */ public function testEvaluateThrowsExceptionWithCustomMessageIfAllOfTheComposedConstraintsEvaluateToFalse(array $constraints): void { $other = 'whatever'; $customDescription = 'Not very happy about the results at this point in time, I have to admit!'; $constraint = new LogicalOr; $constraint->setConstraints($constraints); try { $constraint->evaluate( $other, $customDescription ); } catch (ExpectationFailedException $exception) { $toString = $this->stringify($constraints); $expectedDescription = <<assertEquals($expectedDescription, TestFailure::exceptionToString($exception)); return; } $this->fail(); } /** * @dataProvider providerSucceedingConstraints * * @param Constraint[] $constraints */ public function testEvaluateReturnsNothingIfAnyOfTheComposedConstraintsEvaluateToTrue(array $constraints): void { $constraint = new LogicalOr; $constraint->setConstraints($constraints); $this->assertNull($constraint->evaluate('whatever')); } public function providerFailingConstraints(): \Generator { $values = [ 'single' => [ new \FalsyConstraint, new \FalsyConstraint, new \FalsyConstraint, ], 'multiple' => [ new \FalsyConstraint, new \FalsyConstraint, new \FalsyConstraint, ], ]; foreach ($values as $key => $constraints) { yield $key => [ $constraints, ]; } } public function providerSucceedingConstraints(): \Generator { $values = [ 'single' => [ new \TruthyConstraint, ], 'multiple' => [ new \FalsyConstraint, new \TruthyConstraint, new \FalsyConstraint, ], ]; foreach ($values as $key => $constraints) { yield $key => [ $constraints, ]; } } private function stringify(array $constraints): string { return \implode( ' or ', \array_map(function (Constraint $constraint) { return $constraint->toString(); }, $constraints) ); } } PK!'`1,Framework/Constraint/DirectoryExistsTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class DirectoryExistsTest extends ConstraintTestCase { public function testDefaults(): void { $constraint = new DirectoryExists; $this->assertCount(1, $constraint); $this->assertSame('directory exists', $constraint->toString()); } public function testEvaluateReturnsFalseWhenDirectoryDoesNotExist(): void { $directory = __DIR__ . '/NonExistentDirectory'; $constraint = new DirectoryExists; $this->assertFalse($constraint->evaluate($directory, '', true)); } public function testEvaluateReturnsTrueWhenDirectoryExists(): void { $directory = __DIR__; $constraint = new DirectoryExists; $this->assertTrue($constraint->evaluate($directory, '', true)); } public function testEvaluateThrowsExpectationFailedExceptionWhenDirectoryDoesNotExist(): void { $directory = __DIR__ . '/NonExistentDirectory'; $constraint = new DirectoryExists; try { $constraint->evaluate($directory); } catch (ExpectationFailedException $e) { $this->assertSame( <<fail(); } } PK!,  'Framework/Constraint/LogicalXorTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Framework\Constraint; use PHPUnit\Framework\Constraint\Constraint; use PHPUnit\Framework\Constraint\LogicalXor; use PHPUnit\Framework\TestCase; /** * @small */ final class LogicalXorTest extends TestCase { public function testFromConstraintsReturnsConstraint(): void { $other = 'Foo'; $count = 5; $constraints = \array_map(function () use ($other) { static $count = 0; $constraint = $this->getMockBuilder(Constraint::class)->getMock(); $constraint ->expects($this->once()) ->method('evaluate') ->with($this->identicalTo($other)) ->willReturn($count % 2 === 1); ++$count; return $constraint; }, \array_fill(0, $count, null)); $constraint = LogicalXor::fromConstraints(...$constraints); $this->assertInstanceOf(LogicalXor::class, $constraint); $this->assertTrue($constraint->evaluate($other, '', true)); } public function testSetConstraintsWithNonConstraintsObjectArrayIsTreatedAsIsEqual(): void { $constraint = new LogicalXor; $constraint->setConstraints(['cuckoo']); $this->assertSame('is equal to \'cuckoo\'', $constraint->toString()); } } PK!%" " (Framework/Constraint/ArraySubsetTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; /** * @small */ final class ArraySubsetTest extends ConstraintTestCase { public static function evaluateDataProvider(): array { return [ 'loose array subset and array other' => [ 'expected' => true, 'subset' => ['bar' => 0], 'other' => ['foo' => '', 'bar' => '0'], 'strict' => false, ], 'strict array subset and array other' => [ 'expected' => false, 'subset' => ['bar' => 0], 'other' => ['foo' => '', 'bar' => '0'], 'strict' => true, ], 'loose array subset and ArrayObject other' => [ 'expected' => true, 'subset' => ['bar' => 0], 'other' => new \ArrayObject(['foo' => '', 'bar' => '0']), 'strict' => false, ], 'strict ArrayObject subset and array other' => [ 'expected' => true, 'subset' => new \ArrayObject(['bar' => 0]), 'other' => ['foo' => '', 'bar' => 0], 'strict' => true, ], ]; } /** * @param bool $expected * @param array|\Traversable $subset * @param array|\Traversable $other * @param bool $strict * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @dataProvider evaluateDataProvider */ public function testEvaluate($expected, $subset, $other, $strict): void { $constraint = new ArraySubset($subset, $strict); $this->assertSame($expected, $constraint->evaluate($other, '', true)); } public function testEvaluateWithArrayAccess(): void { $arrayAccess = new \ArrayAccessible(['foo' => 'bar']); $constraint = new ArraySubset(['foo' => 'bar']); $this->assertTrue($constraint->evaluate($arrayAccess, '', true)); } public function testEvaluateFailMessage(): void { $constraint = new ArraySubset(['foo' => 'bar']); try { $constraint->evaluate(['baz' => 'bar'], '', false); $this->fail(\sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); } catch (ExpectationFailedException $expectedException) { $comparisonFailure = $expectedException->getComparisonFailure(); $this->assertNotNull($comparisonFailure); $this->assertStringContainsString("'foo' => 'bar'", $comparisonFailure->getExpectedAsString()); $this->assertStringContainsString("'baz' => 'bar'", $comparisonFailure->getActualAsString()); } } } PK! 0Framework/Constraint/TraversableContainsTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class TraversableContainsTest extends ConstraintTestCase { public function testConstraintTraversableCheckForNonObjectIdentityForDefaultCase(): void { $constraint = new TraversableContains('foo', true, true); $this->assertTrue($constraint->evaluate(['foo'], '', true)); } public function testConstraintTraversableCheckForObjectIdentityForDefaultCase(): void { $constraint = new TraversableContains('foo'); $this->assertTrue($constraint->evaluate([0], '', true)); $this->assertTrue($constraint->evaluate([true], '', true)); } public function testConstraintTraversableCheckForObjectIdentityForPrimitiveType(): void { $constraint = new TraversableContains('foo', true, true); $this->assertFalse($constraint->evaluate([0], '', true)); $this->assertFalse($constraint->evaluate([true], '', true)); } public function testConstraintTraversableWithRightValue(): void { $constraint = new TraversableContains('foo'); $this->assertTrue($constraint->evaluate(['foo'], '', true)); } public function testConstraintTraversableWithFailValue(): void { $constraint = new TraversableContains('foo'); $this->assertFalse($constraint->evaluate(['bar'], '', true)); } public function testConstraintTraversableCountMethods(): void { $constraint = new TraversableContains('foo'); $this->assertCount(1, $constraint); } public function testConstraintTraversableEvaluateMethodWithFailExample(): void { $constraint = new TraversableContains('foo'); try { $constraint->evaluate(['bar']); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintTraversableEvaluateMethodWithFailExample2(): void { $constraint = new TraversableContains('foo' . "\n"); try { $constraint->evaluate(['bar']); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintTraversableEvaluateMethodWithFailExampleWithCustomMessage(): void { $constraint = new TraversableContains('foo'); try { $constraint->evaluate(['bar'], 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintTraversableToStringMethodsWithStdClass(): void { $object = new \stdClass; $constraint = new TraversableContains($object); $this->assertStringMatchesFormat('contains stdClass Object &%s ()', $constraint->toString()); } public function testConstraintTraversableToStringMethods(): void { $constraint = new TraversableContains('foo'); $this->assertEquals("contains 'foo'", $constraint->toString()); } public function testConstraintTraversableToStringMethodsWithSplObjectStorage(): void { $object = new \stdClass; $constraint = new TraversableContains($object); $storage = new \SplObjectStorage; $this->assertFalse($constraint->evaluate($storage, '', true)); $storage->attach($object); $this->assertTrue($constraint->evaluate($storage, '', true)); } public function testConstraintTraversableStdClassForFailSplObjectStorage(): void { $object = new \stdClass; $constraint = new TraversableContains($object); try { $constraint->evaluate(new \SplObjectStorage); } catch (ExpectationFailedException $e) { $this->assertStringMatchesFormat( <<fail(); } public function testConstraintTraversableStdClassForFailSplObjectStorageWithCustomMessage(): void { $object = new \stdClass; $constraint = new TraversableContains($object); try { $constraint->evaluate(new \SplObjectStorage, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertStringMatchesFormat( <<fail(); } } PK!~0*Framework/Constraint/ExceptionCodeTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestFailure; class ExceptionCodeTest extends TestCase { public function testExceptionCodeCanEvaluateExceptions(): void { $exceptionCode = new ExceptionCode(123); $other = new \Exception('bla', 456); try { $exceptionCode->evaluate($other); } catch (ExpectationFailedException $e) { $this->assertEquals( <<assertSame('exception code is ', $exceptionCode->toString()); } } PK!g3l-Framework/Constraint/ExceptionMessageTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\TestCase; /** * @small */ final class ExceptionMessageTest extends TestCase { public function testLiteralMessage(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('A literal exception message'); throw new \Exception('A literal exception message'); } public function testPartialMessageBegin(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('A partial'); throw new \Exception('A partial exception message'); } public function testPartialMessageMiddle(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('partial exception'); throw new \Exception('A partial exception message'); } public function testPartialMessageEnd(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('exception message'); throw new \Exception('A partial exception message'); } public function testEmptyMessageExportToString(): void { $exceptionMessage = new ExceptionMessage(''); $this->assertSame('exception message is empty', $exceptionMessage->toString()); } public function testMessageExportToString(): void { $exceptionMessage = new ExceptionMessage('test'); $this->assertSame('exception message contains ', $exceptionMessage->toString()); } } PK!['Framework/Constraint/LogicalAndTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\Exception; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class LogicalAndTest extends ConstraintTestCase { public function testSetConstraintsRejectsInvalidConstraint(): void { $constraints = [ new \TruthyConstraint, new \FalsyConstraint, new \stdClass, ]; $constraint = new LogicalAnd; $this->expectException(Exception::class); $this->expectExceptionMessage(\sprintf( 'All parameters to %s must be a constraint object.', LogicalAnd::class )); $constraint->setConstraints($constraints); } public function testCountReturnsCountOfComposedConstraints(): void { $counts = [ 3, 5, 8, ]; $constraints = \array_map(function (int $count) { return \CountConstraint::fromCount($count); }, $counts); $constraint = new LogicalAnd; $constraint->setConstraints($constraints); $expected = \array_sum($counts); $this->assertSame($expected, $constraint->count()); } public function testToStringReturnsImplodedStringRepresentationOfComposedConstraintsGluedWithAnd(): void { $names = [ 'is healthy', 'is rich in amino acids', 'is rich in unsaturated fats', ]; $constraints = \array_map(function (string $name) { return \NamedConstraint::fromName($name); }, $names); $constraint = LogicalAnd::fromConstraints(...$constraints); $expected = \implode(' and ', $names); $this->assertSame($expected, $constraint->toString()); } /** * @dataProvider providerFailingConstraints * * @param Constraint[] $constraints */ public function testEvaluateReturnsFalseIfAnyOfTheComposedConstraintsEvaluateToFalse(array $constraints): void { $constraint = new LogicalAnd; $constraint->setConstraints($constraints); $this->assertFalse($constraint->evaluate('whatever', '', true)); } /** * @dataProvider providerSucceedingConstraints * * @param Constraint[] $constraints */ public function testEvaluateReturnsTrueIfAllOfTheComposedConstraintsEvaluateToTrue(array $constraints): void { $constraint = new LogicalAnd; $constraint->setConstraints($constraints); $this->assertTrue($constraint->evaluate('whatever', '', true)); } /** * @dataProvider providerFailingConstraints * * @param Constraint[] $constraints */ public function testEvaluateThrowsExceptionIfAnyOfTheComposedConstraintsEvaluateToFalse(array $constraints): void { $other = 'whatever'; $constraint = new LogicalAnd; $constraint->setConstraints($constraints); try { $constraint->evaluate($other); } catch (ExpectationFailedException $exception) { $toString = $this->stringify($constraints); $expectedDescription = <<assertEquals($expectedDescription, TestFailure::exceptionToString($exception)); return; } $this->fail(); } /** * @dataProvider providerFailingConstraints * * @param Constraint[] $constraints */ public function testEvaluateThrowsExceptionWithCustomMessageIfAnyOfTheComposedConstraintsEvaluateToFalse(array $constraints): void { $other = 'whatever'; $customDescription = 'Not very happy about the results at this point in time, I have to admit!'; $constraint = new LogicalAnd; $constraint->setConstraints($constraints); try { $constraint->evaluate( $other, $customDescription ); } catch (ExpectationFailedException $exception) { $toString = $this->stringify($constraints); $expectedDescription = <<assertEquals($expectedDescription, TestFailure::exceptionToString($exception)); return; } $this->fail(); } /** * @dataProvider providerSucceedingConstraints * * @param Constraint[] $constraints */ public function testEvaluateReturnsNothingIfAllOfTheComposedConstraintsEvaluateToTrue(array $constraints): void { $constraint = new LogicalAnd; $constraint->setConstraints($constraints); $this->assertNull($constraint->evaluate('whatever')); } public function providerFailingConstraints(): \Generator { $values = [ 'single' => [ new \FalsyConstraint, ], 'multiple' => [ new \TruthyConstraint, new \FalsyConstraint, new \TruthyConstraint, ], ]; foreach ($values as $key => $constraints) { yield $key => [ $constraints, ]; } } public function providerSucceedingConstraints(): \Generator { $values = [ 'single' => [ new \TruthyConstraint, ], 'multiple' => [ new \TruthyConstraint, new \TruthyConstraint, new \TruthyConstraint, ], ]; foreach ($values as $key => $constraints) { yield $key => [ $constraints, ]; } } private function stringify(array $constraints): string { return \implode( ' and ', \array_map(function (Constraint $constraint) { return $constraint->toString(); }, $constraints) ); } } PK!4UU&Framework/Constraint/ExceptionTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\TestCase; class ExceptionTest extends TestCase { public function testExceptionCanBeExportedAsString(): void { $exception = new Exception(Exception::class); $this->assertSame('exception of type "' . Exception::class . '"', $exception->toString()); } } PK!)J  -Framework/Constraint/StringStartsWithTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class StringStartsWithTest extends ConstraintTestCase { public function testConstraintStringStartsWithCorrectValueAndReturnResult(): void { $constraint = new StringStartsWith('prefix'); $this->assertTrue($constraint->evaluate('prefixfoo', '', true)); } public function testConstraintStringStartsWithNotCorrectValueAndReturnResult(): void { $constraint = new StringStartsWith('prefix'); $this->assertFalse($constraint->evaluate('error', '', true)); } public function testConstraintStringStartsWithCorrectNumericValueAndReturnResult(): void { $constraint = new StringStartsWith('0E1'); $this->assertTrue($constraint->evaluate('0E1zzz', '', true)); } public function testConstraintStringStartsWithCorrectSingleZeroAndReturnResult(): void { $constraint = new StringStartsWith('0'); $this->assertTrue($constraint->evaluate('0ABC', '', true)); } public function testConstraintStringStartsWithNotCorrectNumericValueAndReturnResult(): void { $constraint = new StringStartsWith('0E1'); $this->assertFalse($constraint->evaluate('0E2zzz', '', true)); } public function testConstraintStringStartsWithToStringMethod(): void { $constraint = new StringStartsWith('prefix'); $this->assertEquals('starts with "prefix"', $constraint->toString()); } public function testConstraintStringStartsWitCountMethod(): void { $constraint = new StringStartsWith('prefix'); $this->assertCount(1, $constraint); } public function testConstraintStringStartsWithNotCorrectValueAndExpectation(): void { $constraint = new StringStartsWith('prefix'); try { $constraint->evaluate('error'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintStringStartsWithNotCorrectValueExceptionAndCustomMessage(): void { $constraint = new StringStartsWith('prefix'); try { $constraint->evaluate('error', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!߶K)Framework/Constraint/IsInstanceOfTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class IsInstanceOfTest extends ConstraintTestCase { public function testConstraintInstanceOf(): void { $constraint = new IsInstanceOf(\stdClass::class); self::assertTrue($constraint->evaluate(new \stdClass, '', true)); } public function testConstraintFailsOnString(): void { $constraint = new IsInstanceOf(\stdClass::class); try { $constraint->evaluate('stdClass'); } catch (ExpectationFailedException $e) { self::assertSame( <<throwException(new \ReflectionException); $constraint = new IsInstanceOf(NotExistingClass::class); self::assertSame( 'is instance of class "PHPUnit\Framework\Constraint\NotExistingClass"', $constraint->toString() ); } } PK!!xd d +Framework/Constraint/StringContainsTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class StringContainsTest extends ConstraintTestCase { public function testConstraintStringContains(): void { $constraint = new StringContains('foo'); $this->assertFalse($constraint->evaluate('barbazbar', '', true)); $this->assertTrue($constraint->evaluate('barfoobar', '', true)); $this->assertEquals('contains "foo"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate('barbazbar'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintStringContainsWhenIgnoreCase(): void { $constraint = new StringContains('oryginał', true); $this->assertFalse($constraint->evaluate('oryginal', '', true)); $this->assertTrue($constraint->evaluate('ORYGINAŁ', '', true)); $this->assertTrue($constraint->evaluate('oryginał', '', true)); $this->assertEquals('contains "oryginał"', $constraint->toString()); $this->assertCount(1, $constraint); $this->expectException(ExpectationFailedException::class); $constraint->evaluate('oryginal'); } public function testConstraintStringContainsForUtf8StringWhenNotIgnoreCase(): void { $constraint = new StringContains('oryginał', false); $this->assertFalse($constraint->evaluate('oryginal', '', true)); $this->assertFalse($constraint->evaluate('ORYGINAŁ', '', true)); $this->assertTrue($constraint->evaluate('oryginał', '', true)); $this->assertEquals('contains "oryginał"', $constraint->toString()); $this->assertCount(1, $constraint); $this->expectException(ExpectationFailedException::class); $constraint->evaluate('oryginal'); } public function testConstraintStringContains2(): void { $constraint = new StringContains('foo'); try { $constraint->evaluate('barbazbar', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testEvaluateEmptyStringInFoo(): void { $stringContains = new StringContains(''); $stringContains->evaluate('foo'); $this->assertSame('contains ""', $stringContains->toString()); } } PK!d$Framework/Constraint/IsEqualTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class IsEqualTest extends ConstraintTestCase { public function testConstraintIsEqual(): void { $constraint = new IsEqual(1); $this->assertTrue($constraint->evaluate(1, '', true)); $this->assertFalse($constraint->evaluate(0, '', true)); $this->assertEquals('is equal to 1', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(0); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } /** * @dataProvider isEqualProvider */ public function testConstraintIsEqual2($expected, $actual, $message): void { $constraint = new IsEqual($expected); try { $constraint->evaluate($actual, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( "custom message\n$message", $this->trimnl(TestFailure::exceptionToString($e)) ); return; } $this->fail(); } public function testConstraintDeltaIsNotZero(): void { $constraint = new IsEqual(15, 1); $this->assertSame('is equal to 15 with delta <1.000000>', $constraint->toString()); } public function isEqualProvider(): array { $a = new \stdClass; $a->foo = 'bar'; $b = new \stdClass; $ahash = \spl_object_hash($a); $bhash = \spl_object_hash($b); $c = new \stdClass; $c->foo = 'bar'; $c->int = 1; $c->array = [0, [1], [2], 3]; $c->related = new \stdClass; $c->related->foo = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"; $c->self = $c; $c->c = $c; $d = new \stdClass; $d->foo = 'bar'; $d->int = 2; $d->array = [0, [4], [2], 3]; $d->related = new \stdClass; $d->related->foo = "a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk"; $d->self = $d; $d->c = $c; $storage1 = new \SplObjectStorage; $storage1->attach($a); $storage1->attach($b); $storage2 = new \SplObjectStorage; $storage2->attach($b); $storage1hash = \spl_object_hash($storage1); $storage2hash = \spl_object_hash($storage2); $dom1 = new \DOMDocument; $dom1->preserveWhiteSpace = false; $dom1->loadXML(''); $dom2 = new \DOMDocument; $dom2->preserveWhiteSpace = false; $dom2->loadXML(''); return [ [1, 0, << 0 + 0 => 1 ) EOF ], [[true], ['true'], << true + 0 => 'true' ) EOF ], [[0, [1], [2], 3], [0, [4], [2], 3], << 0 1 => Array ( - 0 => 1 + 0 => 4 ) 2 => Array (...) 3 => 3 ) EOF ], [$a, [0], << 'bar' ) EOF ], [$c, $d, << 'bar' - 'int' => 1 + 'int' => 2 'array' => Array ( 0 => 0 1 => Array ( - 0 => 1 + 0 => 4 ) 2 => Array (...) 3 => 3 @@ @@ ) 'related' => stdClass Object ( 'foo' => 'a\\n - b\\n + p\\n c\\n d\\n e\\n @@ @@ g\\n h\\n i\\n - j\\n + w\\n k' ) 'self' => stdClass Object (...) 'c' => stdClass Object (...) ) EOF ], [$dom1, $dom2, << - + + + EOF ], [ new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/Chicago')), << Array &0 ( - 'obj' => stdClass Object &$ahash ( - 'foo' => 'bar' - ) - 'inf' => null - ) - '$bhash' => Array &1 ( +SplObjectStorage Object &$storage2hash ( + '$bhash' => Array &0 ( 'obj' => stdClass Object &$bhash () 'inf' => null ) ) EOF ], ]; } /** * Removes spaces in front of newlines * * @param string $string * * @return string */ private function trimnl($string) { return \preg_replace('/[ ]*\n/', "\n", $string); } } PK! * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\TestCase; class LogicalNotTest extends TestCase { public function testNonRestrictedConstructParameterIsTreatedAsIsEqual(): void { $constraint = new LogicalNot('test'); $this->assertSame('is not equal to \'test\'', $constraint->toString()); } } PK!85(Framework/Constraint/IsIdenticalTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class IsIdenticalTest extends ConstraintTestCase { public function testConstraintIsIdentical(): void { $a = new \stdClass; $b = new \stdClass; $constraint = new IsIdentical($a); $this->assertFalse($constraint->evaluate($b, '', true)); $this->assertTrue($constraint->evaluate($a, '', true)); $this->assertEquals('is identical to an object of class "stdClass"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate($b); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsIdentical2(): void { $a = new \stdClass; $b = new \stdClass; $constraint = new IsIdentical($a); try { $constraint->evaluate($b, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsIdentical3(): void { $constraint = new IsIdentical('a'); try { $constraint->evaluate('b', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsIdenticalArrayDiff(): void { $expected = [1, 2, 3, 4, 5, 6]; $actual = [1, 2, 33, 4, 5, 6]; $constraint = new IsIdentical($expected); try { $constraint->evaluate($actual, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertSame( << 1 1 => 2 - 2 => 3 + 2 => 33 3 => 4 4 => 5 5 => 6 ) EOF , TestFailure::exceptionToString($e) ); return; } $this->fail(); } public function testConstraintIsIdenticalNestedArrayDiff(): void { $expected = [ ['A' => 'B'], [ 'C' => [ 'D', 'E', ], ], ]; $actual = [ ['A' => 'C'], [ 'C' => [ 'C', 'E', 'F', ], ], ]; $constraint = new IsIdentical($expected); try { $constraint->evaluate($actual, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( << Array &1 ( - 'A' => 'B' + 'A' => 'C' ) 1 => Array &2 ( 'C' => Array &3 ( - 0 => 'D' + 0 => 'C' 1 => 'E' + 2 => 'F' ) ) ) EOF , TestFailure::exceptionToString($e) ); return; } $this->fail(); } } PK!%Framework/Constraint/SameSizeTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class SameSizeTest extends ConstraintTestCase { public function testConstraintSameSizeWithAnArray(): void { $constraint = new SameSize([1, 2, 3, 4, 5]); $this->assertTrue($constraint->evaluate([6, 7, 8, 9, 10], '', true)); $this->assertFalse($constraint->evaluate([1, 2, 3, 4], '', true)); } public function testConstraintSameSizeWithAnIteratorWhichDoesNotImplementCountable(): void { $constraint = new SameSize(new \TestIterator([1, 2, 3, 4, 5])); $this->assertTrue($constraint->evaluate(new \TestIterator([6, 7, 8, 9, 10]), '', true)); $this->assertFalse($constraint->evaluate(new \TestIterator([1, 2, 3, 4]), '', true)); } public function testConstraintSameSizeWithAnObjectImplementingCountable(): void { $constraint = new SameSize(new \ArrayObject([1, 2, 3, 4, 5])); $this->assertTrue($constraint->evaluate(new \ArrayObject([6, 7, 8, 9, 10]), '', true)); $this->assertFalse($constraint->evaluate(new \ArrayObject([1, 2, 3, 4]), '', true)); } public function testConstraintSameSizeFailing(): void { $constraint = new SameSize([1, 2, 3, 4, 5]); try { $constraint->evaluate([1, 2]); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!WW/Framework/Constraint/ObjectHasAttributeTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class ObjectHasAttributeTest extends ConstraintTestCase { public function testConstraintObjectHasAttribute(): void { $constraint = new ObjectHasAttribute('privateAttribute'); $this->assertTrue($constraint->evaluate(new \ClassWithNonPublicAttributes, '', true)); $this->assertFalse($constraint->evaluate(new \stdClass, '', true)); $this->assertEquals('has attribute "privateAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(new \stdClass); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintObjectHasAttribute2(): void { $constraint = new ObjectHasAttribute('privateAttribute'); try { $constraint->evaluate(new \stdClass, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!:+;;#Framework/Constraint/IsTypeTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\Assert; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class IsTypeTest extends ConstraintTestCase { public function testConstraintIsType(): void { $constraint = Assert::isType('string'); $this->assertFalse($constraint->evaluate(0, '', true)); $this->assertTrue($constraint->evaluate('', '', true)); $this->assertEquals('is of type "string"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(new \stdClass); } catch (ExpectationFailedException $e) { $this->assertStringMatchesFormat( <<trimnl(TestFailure::exceptionToString($e)) ); return; } $this->fail(); } public function testConstraintIsType2(): void { $constraint = Assert::isType('string'); try { $constraint->evaluate(new \stdClass, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertStringMatchesFormat( <<trimnl(TestFailure::exceptionToString($e)) ); return; } $this->fail(); } /** * @dataProvider resources */ public function testConstraintIsResourceTypeEvaluatesCorrectlyWithResources($resource): void { $constraint = Assert::isType('resource'); $this->assertTrue($constraint->evaluate($resource, '', true)); if (\is_resource($resource)) { @\fclose($resource); } } public function resources() { $fh = \fopen(__FILE__, 'r'); \fclose($fh); return [ 'open resource' => [\fopen(__FILE__, 'r')], 'closed resource' => [$fh], ]; } public function testIterableTypeIsSupported(): void { $constraint = Assert::isType('iterable'); $this->assertFalse($constraint->evaluate('', '', true)); $this->assertTrue($constraint->evaluate([], '', true)); $this->assertEquals('is of type "iterable"', $constraint->toString()); } public function testTypeCanBeNull(): void { $constraint = Assert::isType('null'); $this->assertNull($constraint->evaluate(null)); $this->assertEquals('is of type "null"', $constraint->toString()); } public function testTypeCanNotBeAnUndefinedOne(): void { try { Assert::isType('diverse'); } catch (\PHPUnit\Framework\Exception $e) { $this->assertEquals( << is not a valid type. EOF , TestFailure::exceptionToString($e) ); } } /** * Removes spaces in front of newlines * * @param string $string * * @return string */ private function trimnl($string) { return \preg_replace('/[ ]*\n/', "\n", $string); } } PK!ȟ.Framework/Constraint/RegularExpressionTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class RegularExpressionTest extends ConstraintTestCase { public function testConstraintRegularExpression(): void { $constraint = new RegularExpression('/foo/'); $this->assertFalse($constraint->evaluate('barbazbar', '', true)); $this->assertTrue($constraint->evaluate('barfoobar', '', true)); $this->assertEquals('matches PCRE pattern "/foo/"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate('barbazbar'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintRegularExpression2(): void { $constraint = new RegularExpression('/foo/'); try { $constraint->evaluate('barbazbar', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!>î55#Framework/Constraint/IsNullTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class IsNullTest extends ConstraintTestCase { public function testConstraintIsNull(): void { $constraint = new IsNull; $this->assertFalse($constraint->evaluate(0, '', true)); $this->assertTrue($constraint->evaluate(null, '', true)); $this->assertEquals('is null', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(0); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsNull2(): void { $constraint = new IsNull; try { $constraint->evaluate(0, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!blT"Framework/Constraint/CountTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class CountTest extends ConstraintTestCase { public function testCount(): void { $countConstraint = new Count(3); $this->assertTrue($countConstraint->evaluate([1, 2, 3], '', true)); $countConstraint = new Count(0); $this->assertTrue($countConstraint->evaluate([], '', true)); $countConstraint = new Count(2); $it = new \TestIterator([1, 2]); $ia = new \TestIteratorAggregate($it); $ia2 = new \TestIteratorAggregate2($ia); $this->assertTrue($countConstraint->evaluate($it, '', true)); $this->assertTrue($countConstraint->evaluate($ia, '', true)); $this->assertTrue($countConstraint->evaluate($ia2, '', true)); } public function testCountDoesNotChangeIteratorKey(): void { $countConstraint = new Count(2); // test with 1st implementation of Iterator $it = new \TestIterator([1, 2]); $countConstraint->evaluate($it, '', true); $this->assertEquals(1, $it->current()); $it->next(); $countConstraint->evaluate($it, '', true); $this->assertEquals(2, $it->current()); $it->next(); $countConstraint->evaluate($it, '', true); $this->assertFalse($it->valid()); // test with 2nd implementation of Iterator $it = new \TestIterator2([1, 2]); $countConstraint = new Count(2); $countConstraint->evaluate($it, '', true); $this->assertEquals(1, $it->current()); $it->next(); $countConstraint->evaluate($it, '', true); $this->assertEquals(2, $it->current()); $it->next(); $countConstraint->evaluate($it, '', true); $this->assertFalse($it->valid()); // test with IteratorAggregate $it = new \TestIterator([1, 2]); $ia = new \TestIteratorAggregate($it); $countConstraint = new Count(2); $countConstraint->evaluate($ia, '', true); $this->assertEquals(1, $it->current()); $it->next(); $countConstraint->evaluate($ia, '', true); $this->assertEquals(2, $it->current()); $it->next(); $countConstraint->evaluate($ia, '', true); $this->assertFalse($it->valid()); // test with nested IteratorAggregate $it = new \TestIterator([1, 2]); $ia = new \TestIteratorAggregate($it); $ia2 = new \TestIteratorAggregate2($ia); $countConstraint = new Count(2); $countConstraint->evaluate($ia2, '', true); $this->assertEquals(1, $it->current()); $it->next(); $countConstraint->evaluate($ia2, '', true); $this->assertEquals(2, $it->current()); $it->next(); $countConstraint->evaluate($ia2, '', true); $this->assertFalse($it->valid()); } public function testCountGeneratorsDoNotRewind(): void { $generatorMaker = new \TestGeneratorMaker; $countConstraint = new Count(3); $generator = $generatorMaker->create([1, 2, 3]); $this->assertEquals(1, $generator->current()); $countConstraint->evaluate($generator, '', true); $this->assertEquals(null, $generator->current()); $countConstraint = new Count(2); $generator = $generatorMaker->create([1, 2, 3]); $this->assertEquals(1, $generator->current()); $generator->next(); $this->assertEquals(2, $generator->current()); $countConstraint->evaluate($generator, '', true); $this->assertEquals(null, $generator->current()); $countConstraint = new Count(1); $generator = $generatorMaker->create([1, 2, 3]); $this->assertEquals(1, $generator->current()); $generator->next(); $this->assertEquals(2, $generator->current()); $generator->next(); $this->assertEquals(3, $generator->current()); $countConstraint->evaluate($generator, '', true); $this->assertEquals(null, $generator->current()); } public function testCountTraversable(): void { $countConstraint = new Count(5); // DatePeriod is used as an object that is Traversable but does not // implement Iterator or IteratorAggregate. The following ISO 8601 // recurring time interval will yield five total DateTime objects. $datePeriod = new \DatePeriod('R4/2017-05-01T00:00:00Z/P1D'); $this->assertInstanceOf(\Traversable::class, $datePeriod); $this->assertNotInstanceOf(\Iterator::class, $datePeriod); $this->assertNotInstanceOf(\IteratorAggregate::class, $datePeriod); $this->assertTrue($countConstraint->evaluate($datePeriod, '', true)); } public function testCountCanBeExportedToString(): void { $countConstraint = new Count(1); $this->assertEquals('count matches 1', $countConstraint->toString()); } public function testCountEvaluateReturnsNullWithNonCountableAndNonTraversableOther(): void { $countConstraint = new Count(1); try { $this->assertNull($countConstraint->evaluate(1)); } catch (ExpectationFailedException $e) { $this->assertEquals( <<assertTrue($constraint->evaluate(new \EmptyIterator, '', true)); } } PK!N`oo(Framework/Constraint/GreaterThanTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class GreaterThanTest extends ConstraintTestCase { public function testConstraintGreaterThan(): void { $constraint = new GreaterThan(1); $this->assertFalse($constraint->evaluate(0, '', true)); $this->assertTrue($constraint->evaluate(2, '', true)); $this->assertEquals('is greater than 1', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(0); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintGreaterThan2(): void { $constraint = new GreaterThan(1); try { $constraint->evaluate(0, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!5..;Framework/Constraint/StringMatchesFormatDescriptionTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; /** * @small */ final class StringMatchesFormatDescriptionTest extends ConstraintTestCase { public function testConstraintStringMatchesDirectorySeparator(): void { $constraint = new StringMatchesFormatDescription('*%e*'); $this->assertFalse($constraint->evaluate('**', '', true)); $this->assertFalse($constraint->evaluate('*a*', '', true)); $this->assertTrue($constraint->evaluate('*' . \DIRECTORY_SEPARATOR . '*', '', true)); $this->assertEquals('matches PCRE pattern "/^\*\\' . \DIRECTORY_SEPARATOR . '\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesString(): void { $constraint = new StringMatchesFormatDescription('*%s*'); $this->assertFalse($constraint->evaluate('**', '', true)); $this->assertFalse($constraint->evaluate("*\n*", '', true)); $this->assertTrue($constraint->evaluate('***', '', true)); $this->assertTrue($constraint->evaluate('*foo 123 bar*', '', true)); $this->assertEquals('matches PCRE pattern "/^\*[^\r\n]+\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesOptionalString(): void { $constraint = new StringMatchesFormatDescription('*%S*'); $this->assertFalse($constraint->evaluate('*', '', true)); $this->assertFalse($constraint->evaluate("*\n*", '', true)); $this->assertTrue($constraint->evaluate('***', '', true)); $this->assertTrue($constraint->evaluate('*foo 123 bar*', '', true)); $this->assertTrue($constraint->evaluate('**', '', true)); $this->assertEquals('matches PCRE pattern "/^\*[^\r\n]*\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesAnything(): void { $constraint = new StringMatchesFormatDescription('*%a*'); $this->assertFalse($constraint->evaluate('**', '', true)); $this->assertTrue($constraint->evaluate('***', '', true)); $this->assertTrue($constraint->evaluate('*foo 123 bar*', '', true)); $this->assertTrue($constraint->evaluate("*\n*", '', true)); $this->assertEquals('matches PCRE pattern "/^\*.+\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesOptionalAnything(): void { $constraint = new StringMatchesFormatDescription('*%A*'); $this->assertFalse($constraint->evaluate('*', '', true)); $this->assertTrue($constraint->evaluate('***', '', true)); $this->assertTrue($constraint->evaluate('*foo 123 bar*', '', true)); $this->assertTrue($constraint->evaluate("*\n*", '', true)); $this->assertTrue($constraint->evaluate('**', '', true)); $this->assertEquals('matches PCRE pattern "/^\*.*\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesWhitespace(): void { $constraint = new StringMatchesFormatDescription('*%w*'); $this->assertFalse($constraint->evaluate('*', '', true)); $this->assertFalse($constraint->evaluate('*a*', '', true)); $this->assertTrue($constraint->evaluate('* *', '', true)); $this->assertTrue($constraint->evaluate("*\t\n*", '', true)); $this->assertTrue($constraint->evaluate('**', '', true)); $this->assertEquals('matches PCRE pattern "/^\*\s*\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesInteger(): void { $constraint = new StringMatchesFormatDescription('*%i*'); $this->assertFalse($constraint->evaluate('**', '', true)); $this->assertFalse($constraint->evaluate('*a*', '', true)); $this->assertFalse($constraint->evaluate('*1.0*', '', true)); $this->assertTrue($constraint->evaluate('*0*', '', true)); $this->assertTrue($constraint->evaluate('*12*', '', true)); $this->assertTrue($constraint->evaluate('*-1*', '', true)); $this->assertTrue($constraint->evaluate('*+2*', '', true)); $this->assertEquals('matches PCRE pattern "/^\*[+-]?\d+\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesUnsignedInt(): void { $constraint = new StringMatchesFormatDescription('*%d*'); $this->assertFalse($constraint->evaluate('**', '', true)); $this->assertFalse($constraint->evaluate('*a*', '', true)); $this->assertFalse($constraint->evaluate('*1.0*', '', true)); $this->assertFalse($constraint->evaluate('*-1*', '', true)); $this->assertFalse($constraint->evaluate('*+2*', '', true)); $this->assertTrue($constraint->evaluate('*0*', '', true)); $this->assertTrue($constraint->evaluate('*12*', '', true)); $this->assertEquals('matches PCRE pattern "/^\*\d+\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesHexadecimal(): void { $constraint = new StringMatchesFormatDescription('*%x*'); $this->assertFalse($constraint->evaluate('**', '', true)); $this->assertFalse($constraint->evaluate('***', '', true)); $this->assertFalse($constraint->evaluate('*g*', '', true)); $this->assertFalse($constraint->evaluate('*1.0*', '', true)); $this->assertFalse($constraint->evaluate('*-1*', '', true)); $this->assertFalse($constraint->evaluate('*+2*', '', true)); $this->assertTrue($constraint->evaluate('*0f0f0f*', '', true)); $this->assertTrue($constraint->evaluate('*0*', '', true)); $this->assertTrue($constraint->evaluate('*12*', '', true)); $this->assertTrue($constraint->evaluate('*a*', '', true)); $this->assertEquals('matches PCRE pattern "/^\*[0-9a-fA-F]+\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesFloat(): void { $constraint = new StringMatchesFormatDescription('*%f*'); $this->assertFalse($constraint->evaluate('**', '', true)); $this->assertFalse($constraint->evaluate('***', '', true)); $this->assertFalse($constraint->evaluate('*a*', '', true)); $this->assertTrue($constraint->evaluate('*1.0*', '', true)); $this->assertTrue($constraint->evaluate('*0*', '', true)); $this->assertTrue($constraint->evaluate('*12*', '', true)); $this->assertTrue($constraint->evaluate('*.1*', '', true)); $this->assertTrue($constraint->evaluate('*1.*', '', true)); $this->assertTrue($constraint->evaluate('*2e3*', '', true)); $this->assertTrue($constraint->evaluate('*-2.34e-56*', '', true)); $this->assertTrue($constraint->evaluate('*+2.34e+56*', '', true)); $this->assertEquals('matches PCRE pattern "/^\*[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesCharacter(): void { $constraint = new StringMatchesFormatDescription('*%c*'); $this->assertFalse($constraint->evaluate('**', '', true)); $this->assertFalse($constraint->evaluate('*ab*', '', true)); $this->assertTrue($constraint->evaluate('***', '', true)); $this->assertTrue($constraint->evaluate('*a*', '', true)); $this->assertTrue($constraint->evaluate('*g*', '', true)); $this->assertTrue($constraint->evaluate('*0*', '', true)); $this->assertTrue($constraint->evaluate('*2*', '', true)); $this->assertTrue($constraint->evaluate('* *', '', true)); $this->assertTrue($constraint->evaluate("*\n*", '', true)); $this->assertEquals('matches PCRE pattern "/^\*.\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesEscapedPercent(): void { $constraint = new StringMatchesFormatDescription('%%,%%e,%%s,%%S,%%a,%%A,%%w,%%i,%%d,%%x,%%f,%%c,%%Z,%%%%,%%'); $this->assertFalse($constraint->evaluate('%%,%' . \DIRECTORY_SEPARATOR . ',%*,%*,%*,%*,% ,%0,%0,%0f0f0f,%1.0,%*,%%Z,%%%%,%%', '', true)); $this->assertTrue($constraint->evaluate('%,%e,%s,%S,%a,%A,%w,%i,%d,%x,%f,%c,%Z,%%,%', '', true)); $this->assertEquals('matches PCRE pattern "/^%,%e,%s,%S,%a,%A,%w,%i,%d,%x,%f,%c,%Z,%%,%$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesEscapedPercentThenPlaceholder(): void { $constraint = new StringMatchesFormatDescription('%%%e,%%%s,%%%S,%%%a,%%%A,%%%w,%%%i,%%%d,%%%x,%%%f,%%%c'); $this->assertFalse($constraint->evaluate('%%e,%%s,%%S,%%a,%%A,%%w,%%i,%%d,%%x,%%f,%%c', '', true)); $this->assertTrue($constraint->evaluate('%' . \DIRECTORY_SEPARATOR . ',%*,%*,%*,%*,% ,%0,%0,%0f0f0f,%1.0,%*', '', true)); $this->assertEquals('matches PCRE pattern "/^%\\' . \DIRECTORY_SEPARATOR . ',%[^\r\n]+,%[^\r\n]*,%.+,%.*,%\s*,%[+-]?\d+,%\d+,%[0-9a-fA-F]+,%[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?,%.$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesSlash(): void { $constraint = new StringMatchesFormatDescription('/'); $this->assertFalse($constraint->evaluate('\\/', '', true)); $this->assertTrue($constraint->evaluate('/', '', true)); $this->assertEquals('matches PCRE pattern "/^\\/$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesBackslash(): void { $constraint = new StringMatchesFormatDescription('\\'); $this->assertFalse($constraint->evaluate('\\\\', '', true)); $this->assertTrue($constraint->evaluate('\\', '', true)); $this->assertEquals('matches PCRE pattern "/^\\\\$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesBackslashSlash(): void { $constraint = new StringMatchesFormatDescription('\\/'); $this->assertFalse($constraint->evaluate('/', '', true)); $this->assertTrue($constraint->evaluate('\\/', '', true)); $this->assertEquals('matches PCRE pattern "/^\\\\\\/$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } public function testConstraintStringMatchesNewline(): void { $constraint = new StringMatchesFormatDescription("\r\n"); $this->assertFalse($constraint->evaluate("*\r\n", '', true)); $this->assertTrue($constraint->evaluate("\r\n", '', true)); $this->assertEquals("matches PCRE pattern \"/^\n$/s\"", $constraint->toString()); $this->assertCount(1, $constraint); } public function testFailureMessageWithNewlines(): void { $constraint = new StringMatchesFormatDescription("%c\nfoo\n%c"); try { $constraint->evaluate("*\nbar\n*"); $this->fail('Expected ExpectationFailedException, but it was not thrown.'); } catch (ExpectationFailedException $e) { $expected = <<assertEquals($expected, $e->getMessage()); } } } PK!  +Framework/Constraint/StringEndsWithTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class StringEndsWithTest extends ConstraintTestCase { public function testConstraintStringEndsWithCorrectValueAndReturnResult(): void { $constraint = new StringEndsWith('suffix'); $this->assertTrue($constraint->evaluate('foosuffix', '', true)); } public function testConstraintStringEndsWithNotCorrectValueAndReturnResult(): void { $constraint = new StringEndsWith('suffix'); $this->assertFalse($constraint->evaluate('suffixerror', '', true)); } public function testConstraintStringEndsWithCorrectNumericValueAndReturnResult(): void { $constraint = new StringEndsWith('0E1'); $this->assertTrue($constraint->evaluate('zzz0E1', '', true)); } public function testConstraintStringEndsWithNotCorrectNumericValueAndReturnResult(): void { $constraint = new StringEndsWith('0E1'); $this->assertFalse($constraint->evaluate('zzz0E2', '', true)); } public function testConstraintStringEndsWithToStringMethod(): void { $constraint = new StringEndsWith('suffix'); $this->assertEquals('ends with "suffix"', $constraint->toString()); } public function testConstraintStringEndsWithCountMethod(): void { $constraint = new StringEndsWith('suffix'); $this->assertCount(1, $constraint); } public function testConstraintStringEndsWithNotCorrectValueAndExpectation(): void { $constraint = new StringEndsWith('suffix'); try { $constraint->evaluate('error'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintStringEndsWithNotCorrectValueExceptionAndCustomMessage(): void { $constraint = new StringEndsWith('suffix'); try { $constraint->evaluate('error', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!JJa@@3Framework/Constraint/ExceptionMessageRegExpTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\TestCase; /** * @small */ final class ExceptionMessageRegExpTest extends TestCase { public function testRegexMessage(): void { $this->expectException(\Exception::class); $this->expectExceptionMessageMatches('/^A polymorphic \w+ message/'); throw new \Exception('A polymorphic exception message'); } public function testRegexMessageExtreme(): void { $this->expectException(\Exception::class); $this->expectExceptionMessageMatches('/^a poly[a-z]+ [a-zA-Z0-9_]+ me(s){2}age$/i'); throw new \Exception('A polymorphic exception message'); } /** * @runInSeparateProcess * @requires extension xdebug */ public function testMessageXdebugScreamCompatibility(): void { \ini_set('xdebug.scream', '1'); $this->expectException(\Exception::class); $this->expectExceptionMessageMatches('#Screaming preg_match#'); throw new \Exception('Screaming preg_match'); } public function testRegExMessageCanBeExportedAsString(): void { $exceptionMessageReExp = new ExceptionMessageRegularExpression('/^a poly[a-z]+ [a-zA-Z0-9_]+ me(s){2}age$/i'); $this->assertSame('exception message matches ', $exceptionMessageReExp->toString()); } } PK!|E(Framework/Constraint/ArrayHasKeyTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class ArrayHasKeyTest extends ConstraintTestCase { public function testConstraintArrayHasKey(): void { $constraint = new ArrayHasKey(0); $this->assertFalse($constraint->evaluate([], '', true)); $this->assertEquals('has the key 0', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate([]); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintArrayHasKey2(): void { $constraint = new ArrayHasKey(0); try { $constraint->evaluate([], 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintArrayHasKey0(): void { $constraint = new ArrayHasKey(0); try { $constraint->evaluate(0, ''); } catch (ExpectationFailedException $e) { $this->assertEquals( << * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; use PHPUnit\Util\Json; /** * @small */ final class JsonMatchesTest extends ConstraintTestCase { public static function evaluateDataprovider(): array { return [ 'valid JSON' => [true, \json_encode(['Mascott' => 'Tux']), \json_encode(['Mascott' => 'Tux'])], 'error syntax' => [false, '{"Mascott"::}', \json_encode(['Mascott' => 'Tux'])], 'error UTF-8' => [false, \json_encode('\xB1\x31'), \json_encode(['Mascott' => 'Tux'])], 'invalid JSON in class instantiation' => [false, \json_encode(['Mascott' => 'Tux']), '{"Mascott"::}'], 'string type not equals number' => [false, '{"age": "5"}', '{"age": 5}'], 'string type not equals boolean' => [false, '{"age": "true"}', '{"age": true}'], 'string type not equals null' => [false, '{"age": "null"}', '{"age": null}'], 'object fields are unordered' => [true, '{"first":1, "second":"2"}', '{"second":"2", "first":1}'], 'child object fields are unordered' => [true, '{"Mascott": {"name":"Tux", "age":5}}', '{"Mascott": {"age":5, "name":"Tux"}}'], 'null field different from missing field' => [false, '{"present": true, "missing": null}', '{"present": true}'], 'array elements are ordered' => [false, '["first", "second"]', '["second", "first"]'], 'single boolean valid json' => [true, 'true', 'true'], 'single number valid json' => [true, '5.3', '5.3'], 'single null valid json' => [true, 'null', 'null'], 'objects are not arrays' => [false, '{}', '[]'], ]; } public static function evaluateThrowsExpectationFailedExceptionWhenJsonIsValidButDoesNotMatchDataprovider(): array { return [ 'error UTF-8' => [\json_encode('\xB1\x31'), \json_encode(['Mascott' => 'Tux'])], 'string type not equals number' => ['{"age": "5"}', '{"age": 5}'], 'string type not equals boolean' => ['{"age": "true"}', '{"age": true}'], 'string type not equals null' => ['{"age": "null"}', '{"age": null}'], 'null field different from missing field' => ['{"missing": null, "present": true}', '{"present": true}'], 'array elements are ordered' => ['["first", "second"]', '["second", "first"]'], ]; } /** * @dataProvider evaluateDataprovider * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testEvaluate($expected, $jsonOther, $jsonValue): void { $constraint = new JsonMatches($jsonValue); $this->assertEquals($expected, $constraint->evaluate($jsonOther, '', true)); } /** * @dataProvider evaluateThrowsExpectationFailedExceptionWhenJsonIsValidButDoesNotMatchDataprovider * * @throws ExpectationFailedException * @throws \PHPUnit\Framework\AssertionFailedError * @throws \PHPUnit\Framework\Exception * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testEvaluateThrowsExpectationFailedExceptionWhenJsonIsValidButDoesNotMatch($jsonOther, $jsonValue): void { $constraint = new JsonMatches($jsonValue); try { $constraint->evaluate($jsonOther, '', false); $this->fail(\sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); } catch (ExpectationFailedException $expectedException) { $comparisonFailure = $expectedException->getComparisonFailure(); $this->assertNotNull($comparisonFailure); $this->assertSame(Json::prettify($jsonOther), $comparisonFailure->getActualAsString()); $this->assertSame(Json::prettify($jsonValue), $comparisonFailure->getExpectedAsString()); $this->assertSame('Failed asserting that two json values are equal.', $comparisonFailure->getMessage()); } } public function testToString(): void { $jsonValue = \json_encode(['Mascott' => 'Tux']); $constraint = new JsonMatches($jsonValue); $this->assertEquals('matches JSON string "' . $jsonValue . '"', $constraint->toString()); } public function testFailErrorWithInvalidValueAndOther(): void { $constraint = new JsonMatches('{"Mascott"::}'); try { $constraint->evaluate('{"Mascott"::}', '', false); $this->fail(\sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); } catch (ExpectationFailedException $e) { $this->assertEquals( <<evaluate('{"Mascott":"Tux"}', '', false); $this->fail(\sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); } catch (ExpectationFailedException $e) { $this->assertEquals( <<evaluate('{"obj": {}, "val": 2}', '', false); } catch (ExpectationFailedException $e) { $this->assertEquals( <<evaluate('{"obj": {"y": 2, "x": 1}, "val": 2}', '', false); } catch (ExpectationFailedException $e) { $this->assertEquals( << * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; /** * @small */ final class CallbackTest extends ConstraintTestCase { public static function staticCallbackReturningTrue() { return true; } public function callbackReturningTrue() { return true; } public function testConstraintCallback(): void { $closureReflect = function ($parameter) { return $parameter; }; $closureWithoutParameter = function () { return true; }; $constraint = new Callback($closureWithoutParameter); $this->assertTrue($constraint->evaluate('', '', true)); $constraint = new Callback($closureReflect); $this->assertTrue($constraint->evaluate(true, '', true)); $this->assertFalse($constraint->evaluate(false, '', true)); $callback = [$this, 'callbackReturningTrue']; $constraint = new Callback($callback); $this->assertTrue($constraint->evaluate(false, '', true)); $callback = [self::class, 'staticCallbackReturningTrue']; $constraint = new Callback($callback); $this->assertTrue($constraint->evaluate(null, '', true)); $this->assertEquals('is accepted by specified callback', $constraint->toString()); } public function testConstraintCallbackFailure(): void { $constraint = new Callback(function () { return false; }); $this->expectException(ExpectationFailedException::class); $this->expectExceptionMessage('Failed asserting that \'This fails\' is accepted by specified callback.'); $constraint->evaluate('This fails'); } } PK!AA'Framework/Constraint/IsReadableTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class IsReadableTest extends ConstraintTestCase { public function testConstraintIsReadable(): void { $constraint = new IsReadable; $this->assertFalse($constraint->evaluate('foo', '', true)); $this->assertEquals('is readable', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate('foo'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!Suu4Framework/Constraint/ClassHasStaticAttributeTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class ClassHasStaticAttributeTest extends ConstraintTestCase { public function testConstraintClassHasStaticAttribute(): void { $constraint = new ClassHasStaticAttribute('privateStaticAttribute'); $this->assertTrue($constraint->evaluate(\ClassWithNonPublicAttributes::class, '', true)); $this->assertFalse($constraint->evaluate(\stdClass::class, '', true)); $this->assertEquals('has static attribute "privateStaticAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(\stdClass::class); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintClassHasStaticAttribute2(): void { $constraint = new ClassHasStaticAttribute('foo'); try { $constraint->evaluate(\stdClass::class, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!n%WW%Framework/Constraint/LessThanTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; /** * @small */ final class LessThanTest extends ConstraintTestCase { public function testConstraintLessThan(): void { $constraint = new LessThan(1); $this->assertTrue($constraint->evaluate(0, '', true)); $this->assertFalse($constraint->evaluate(1, '', true)); $this->assertEquals('is less than 1', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(1); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintLessThan2(): void { $constraint = new LessThan(1); try { $constraint->evaluate(1, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } } PK!SnFramework/TestCaseTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\Stub; use PHPUnit\Runner\BaseTestRunner; use PHPUnit\Util\Test as TestUtil; /** * @small */ final class TestCaseTest extends TestCase { protected static $testStatic = 456; protected $backupGlobalsBlacklist = ['i', 'singleton']; public static function setUpBeforeClass(): void { $GLOBALS['a'] = 'a'; $_ENV['b'] = 'b'; $_POST['c'] = 'c'; $_GET['d'] = 'd'; $_COOKIE['e'] = 'e'; $_SERVER['f'] = 'f'; $_FILES['g'] = 'g'; $_REQUEST['h'] = 'h'; $GLOBALS['i'] = 'i'; } public static function tearDownAfterClass(): void { unset( $GLOBALS['a'], $_ENV['b'], $_POST['c'], $_GET['d'], $_COOKIE['e'], $_SERVER['f'], $_FILES['g'], $_REQUEST['h'], $GLOBALS['i'] ); } public function testCaseToString(): void { $this->assertEquals( 'PHPUnit\Framework\TestCaseTest::testCaseToString', $this->toString() ); } public function testSuccess(): void { $test = new \Success; $result = $test->run(); $this->assertEquals(BaseTestRunner::STATUS_PASSED, $test->getStatus()); $this->assertEquals(0, $result->errorCount()); $this->assertEquals(0, $result->failureCount()); $this->assertEquals(0, $result->skippedCount()); $this->assertCount(1, $result); } public function testFailure(): void { $test = new \Failure; $result = $test->run(); $this->assertEquals(BaseTestRunner::STATUS_FAILURE, $test->getStatus()); $this->assertEquals(0, $result->errorCount()); $this->assertEquals(1, $result->failureCount()); $this->assertEquals(0, $result->skippedCount()); $this->assertCount(1, $result); } public function testError(): void { $test = new \TestError; $result = $test->run(); $this->assertEquals(BaseTestRunner::STATUS_ERROR, $test->getStatus()); $this->assertEquals(1, $result->errorCount()); $this->assertEquals(0, $result->failureCount()); $this->assertEquals(0, $result->skippedCount()); $this->assertCount(1, $result); } public function testSkipped(): void { $test = new \TestSkipped; $result = $test->run(); $this->assertEquals(BaseTestRunner::STATUS_SKIPPED, $test->getStatus()); $this->assertEquals('Skipped test', $test->getStatusMessage()); $this->assertEquals(0, $result->errorCount()); $this->assertEquals(0, $result->failureCount()); $this->assertEquals(1, $result->skippedCount()); $this->assertCount(1, $result); } public function testIncomplete(): void { $test = new \TestIncomplete; $result = $test->run(); $this->assertEquals(BaseTestRunner::STATUS_INCOMPLETE, $test->getStatus()); $this->assertEquals('Incomplete test', $test->getStatusMessage()); $this->assertEquals(0, $result->errorCount()); $this->assertEquals(0, $result->failureCount()); $this->assertEquals(0, $result->skippedCount()); $this->assertCount(1, $result); } public function testExceptionInSetUp(): void { $test = new \ExceptionInSetUpTest('testSomething'); $test->run(); $this->assertTrue($test->setUp); $this->assertFalse($test->assertPreConditions); $this->assertFalse($test->testSomething); $this->assertFalse($test->assertPostConditions); $this->assertTrue($test->tearDown); } public function testExceptionInAssertPreConditions(): void { $test = new \ExceptionInAssertPreConditionsTest('testSomething'); $test->run(); $this->assertTrue($test->setUp); $this->assertTrue($test->assertPreConditions); $this->assertFalse($test->testSomething); $this->assertFalse($test->assertPostConditions); $this->assertTrue($test->tearDown); } public function testExceptionInTest(): void { $test = new \ExceptionInTest('testSomething'); $test->run(); $this->assertTrue($test->setUp); $this->assertTrue($test->assertPreConditions); $this->assertTrue($test->testSomething); $this->assertFalse($test->assertPostConditions); $this->assertTrue($test->tearDown); } public function testExceptionInAssertPostConditions(): void { $test = new \ExceptionInAssertPostConditionsTest('testSomething'); $test->run(); $this->assertTrue($test->setUp); $this->assertTrue($test->assertPreConditions); $this->assertTrue($test->testSomething); $this->assertTrue($test->assertPostConditions); $this->assertTrue($test->tearDown); } public function testExceptionInTearDown(): void { $test = new \ExceptionInTearDownTest('testSomething'); $test->run(); $this->assertTrue($test->setUp); $this->assertTrue($test->assertPreConditions); $this->assertTrue($test->testSomething); $this->assertTrue($test->assertPostConditions); $this->assertTrue($test->tearDown); $this->assertEquals(BaseTestRunner::STATUS_ERROR, $test->getStatus()); $this->assertSame('throw Exception in tearDown()', $test->getStatusMessage()); } public function testExceptionInTestIsDetectedInTeardown(): void { $test = new \ExceptionInTestDetectedInTeardown('testSomething'); $test->run(); $this->assertTrue($test->exceptionDetected); } public function testNoArgTestCasePasses(): void { $result = new TestResult; $t = new TestSuite(\NoArgTestCaseTest::class); $t->run($result); $this->assertCount(1, $result); $this->assertEquals(0, $result->failureCount()); $this->assertEquals(0, $result->errorCount()); } public function testWasRun(): void { $test = new \WasRun; $test->run(); $this->assertTrue($test->wasRun); } public function testException(): void { $test = new \ThrowExceptionTestCase('test'); $test->expectException(\RuntimeException::class); $result = $test->run(); $this->assertCount(1, $result); $this->assertTrue($result->wasSuccessful()); } public function testExpectExceptionAllowsAccessingExpectedException(): void { $exception = \RuntimeException::class; $test = new \ThrowExceptionTestCase('test'); $test->expectException($exception); $this->assertSame($exception, $test->getExpectedException()); } public function testExpectExceptionCodeWithSameCode(): void { $test = new \ThrowExceptionTestCase('test'); $test->expectExceptionCode(0); $result = $test->run(); $this->assertCount(1, $result); $this->assertTrue($result->wasSuccessful()); } public function testExpectExceptionCodeWithDifferentCode(): void { $test = new \ThrowExceptionTestCase('test'); $test->expectExceptionCode(9000); $result = $test->run(); $this->assertCount(1, $result); $this->assertFalse($result->wasSuccessful()); } public function testExpectExceptionCodeAllowsAccessingExpectedExceptionCode(): void { $code = 9000; $test = new \ThrowExceptionTestCase('test'); $test->expectExceptionCode($code); $this->assertSame($code, $test->getExpectedExceptionCode()); } public function testExceptionWithEmptyMessage(): void { $test = new \ThrowExceptionTestCase('test'); $test->expectException(\RuntimeException::class); $result = $test->run(); $this->assertCount(1, $result); $this->assertTrue($result->wasSuccessful()); } public function testExceptionWithNullMessage(): void { $test = new \ThrowExceptionTestCase('test'); $test->expectException(\RuntimeException::class); $result = $test->run(); $this->assertCount(1, $result); $this->assertTrue($result->wasSuccessful()); } public function testExceptionWithMessage(): void { $test = new \ThrowExceptionTestCase('test'); $test->expectException(\RuntimeException::class); $test->expectExceptionMessage('A runtime error occurred'); $result = $test->run(); $this->assertCount(1, $result); $this->assertTrue($result->wasSuccessful()); } public function testExceptionWithWrongMessage(): void { $test = new \ThrowExceptionTestCase('test'); $test->expectException(\RuntimeException::class); $test->expectExceptionMessage('A logic error occurred'); $result = $test->run(); $this->assertEquals(1, $result->failureCount()); $this->assertCount(1, $result); $this->assertEquals( "Failed asserting that exception message 'A runtime error occurred' contains 'A logic error occurred'.", $test->getStatusMessage() ); } public function testExpectExceptionMessageAllowsAccessingExpectedExceptionMessage(): void { $message = 'A runtime error occurred'; $test = new \ThrowExceptionTestCase('test'); $test->expectExceptionMessage($message); $this->assertSame($message, $test->getExpectedExceptionMessage()); } public function testExceptionWithRegexpMessage(): void { $test = new \ThrowExceptionTestCase('test'); $test->expectException(\RuntimeException::class); $test->expectExceptionMessageMatches('/runtime .*? occurred/'); $result = $test->run(); $this->assertCount(1, $result); $this->assertTrue($result->wasSuccessful()); } public function testExpectExceptionMessageRegExpAllowsAccessingExpectedExceptionRegExp(): void { $messageRegExp = '/runtime .*? occurred/'; $test = new \ThrowExceptionTestCase('test'); $test->expectExceptionMessageMatches($messageRegExp); $this->assertSame($messageRegExp, $test->getExpectedExceptionMessageRegExp()); } public function testExceptionWithWrongRegexpMessage(): void { $test = new \ThrowExceptionTestCase('test'); $test->expectException(\RuntimeException::class); $test->expectExceptionMessageMatches('/logic .*? occurred/'); $result = $test->run(); $this->assertEquals(1, $result->failureCount()); $this->assertCount(1, $result); $this->assertEquals( "Failed asserting that exception message 'A runtime error occurred' matches '/logic .*? occurred/'.", $test->getStatusMessage() ); } public function testExceptionWithInvalidRegexpMessage(): void { $test = new \ThrowExceptionTestCase('test'); $test->expectException(\RuntimeException::class); $test->expectExceptionMessageMatches('#runtime .*? occurred/'); $test->run(); $this->assertEquals( "Invalid expected exception message regex given: '#runtime .*? occurred/'", $test->getStatusMessage() ); } public function testExpectExceptionObjectWithDifferentExceptionClass(): void { $exception = new \InvalidArgumentException( 'Cannot compute at this time.', 9000 ); $test = new \ThrowExceptionTestCase('testWithExpectExceptionObject'); $test->expectExceptionObject($exception); $result = $test->run(); $this->assertCount(1, $result); $this->assertFalse($result->wasSuccessful()); } public function testExpectExceptionObjectWithDifferentExceptionMessage(): void { $exception = new \RuntimeException( 'This is fine!', 9000 ); $test = new \ThrowExceptionTestCase('testWithExpectExceptionObject'); $test->expectExceptionObject($exception); $result = $test->run(); $this->assertCount(1, $result); $this->assertFalse($result->wasSuccessful()); } public function testExpectExceptionObjectWithDifferentExceptionCode(): void { $exception = new \RuntimeException( 'Cannot compute at this time.', 9001 ); $test = new \ThrowExceptionTestCase('testWithExpectExceptionObject'); $test->expectExceptionObject($exception); $result = $test->run(); $this->assertCount(1, $result); $this->assertFalse($result->wasSuccessful()); } public function testExpectExceptionObjectWithEqualException(): void { $exception = new \RuntimeException( 'Cannot compute at this time', 9000 ); $test = new \ThrowExceptionTestCase('testWithExpectExceptionObject'); $test->expectExceptionObject($exception); $result = $test->run(); $this->assertCount(1, $result); $this->assertTrue($result->wasSuccessful()); } public function testExpectExceptionObjectAllowsAccessingExpectedExceptionDetails(): void { $exception = new \RuntimeException( 'Cannot compute at this time', 9000 ); $test = new \ThrowExceptionTestCase('testWithExpectExceptionObject'); $test->expectExceptionObject($exception); $this->assertSame(\get_class($exception), $test->getExpectedException()); $this->assertSame($exception->getCode(), $test->getExpectedExceptionCode()); $this->assertSame($exception->getMessage(), $test->getExpectedExceptionMessage()); } public function testNoException(): void { $test = new \ThrowNoExceptionTestCase('test'); $test->expectException(\RuntimeException::class); $result = $test->run(); $this->assertEquals(1, $result->failureCount()); $this->assertCount(1, $result); } public function testWrongException(): void { $test = new \ThrowExceptionTestCase('test'); $test->expectException(\InvalidArgumentException::class); $result = $test->run(); $this->assertEquals(1, $result->failureCount()); $this->assertCount(1, $result); } public function testDoesNotPerformAssertions(): void { $test = new \DoNoAssertionTestCase('testNothing'); $test->expectNotToPerformAssertions(); $result = $test->run(); $this->assertEquals(0, $result->riskyCount()); $this->assertCount(1, $result); } /** * @backupGlobals enabled */ public function testGlobalsBackupPre(): void { global $a; global $i; $this->assertEquals('a', $a); $this->assertEquals('a', $GLOBALS['a']); $this->assertEquals('b', $_ENV['b']); $this->assertEquals('c', $_POST['c']); $this->assertEquals('d', $_GET['d']); $this->assertEquals('e', $_COOKIE['e']); $this->assertEquals('f', $_SERVER['f']); $this->assertEquals('g', $_FILES['g']); $this->assertEquals('h', $_REQUEST['h']); $this->assertEquals('i', $i); $this->assertEquals('i', $GLOBALS['i']); $GLOBALS['a'] = 'aa'; $GLOBALS['foo'] = 'bar'; $_ENV['b'] = 'bb'; $_POST['c'] = 'cc'; $_GET['d'] = 'dd'; $_COOKIE['e'] = 'ee'; $_SERVER['f'] = 'ff'; $_FILES['g'] = 'gg'; $_REQUEST['h'] = 'hh'; $GLOBALS['i'] = 'ii'; $this->assertEquals('aa', $a); $this->assertEquals('aa', $GLOBALS['a']); $this->assertEquals('bar', $GLOBALS['foo']); $this->assertEquals('bb', $_ENV['b']); $this->assertEquals('cc', $_POST['c']); $this->assertEquals('dd', $_GET['d']); $this->assertEquals('ee', $_COOKIE['e']); $this->assertEquals('ff', $_SERVER['f']); $this->assertEquals('gg', $_FILES['g']); $this->assertEquals('hh', $_REQUEST['h']); $this->assertEquals('ii', $i); $this->assertEquals('ii', $GLOBALS['i']); } /** * @depends testGlobalsBackupPre */ public function testGlobalsBackupPost(): void { global $a; global $i; $this->assertEquals('a', $a); $this->assertEquals('a', $GLOBALS['a']); $this->assertEquals('b', $_ENV['b']); $this->assertEquals('c', $_POST['c']); $this->assertEquals('d', $_GET['d']); $this->assertEquals('e', $_COOKIE['e']); $this->assertEquals('f', $_SERVER['f']); $this->assertEquals('g', $_FILES['g']); $this->assertEquals('h', $_REQUEST['h']); $this->assertEquals('ii', $i); $this->assertEquals('ii', $GLOBALS['i']); $this->assertArrayNotHasKey('foo', $GLOBALS); } /** * @backupGlobals enabled * @backupStaticAttributes enabled * @depends testGlobalsBackupPost * * @doesNotPerformAssertions */ public function testStaticAttributesBackupPre(): void { $GLOBALS['singleton'] = \Singleton::getInstance(); $GLOBALS['i'] = 'set by testStaticAttributesBackupPre'; $GLOBALS['j'] = 'reset by backup'; self::$testStatic = 123; } /** * @depends testStaticAttributesBackupPre */ public function testStaticAttributesBackupPost(): void { // Snapshots made by @backupGlobals $this->assertSame(\Singleton::getInstance(), $GLOBALS['singleton']); $this->assertSame('set by testStaticAttributesBackupPre', $GLOBALS['i']); // Reset global $this->assertArrayNotHasKey('j', $GLOBALS); // Static reset to original state by @backupStaticAttributes $this->assertSame(456, self::$testStatic); } public function testIsInIsolationReturnsFalse(): void { $test = new \IsolationTest('testIsInIsolationReturnsFalse'); $result = $test->run(); $this->assertCount(1, $result); $this->assertTrue($result->wasSuccessful()); } public function testIsInIsolationReturnsTrue(): void { $test = new \IsolationTest('testIsInIsolationReturnsTrue'); $test->setRunTestInSeparateProcess(true); $result = $test->run(); $this->assertCount(1, $result); $this->assertTrue($result->wasSuccessful()); } public function testExpectOutputStringFooActualFoo(): void { $test = new \OutputTestCase('testExpectOutputStringFooActualFoo'); $result = $test->run(); $this->assertCount(1, $result); $this->assertTrue($result->wasSuccessful()); } public function testExpectOutputStringFooActualBar(): void { $test = new \OutputTestCase('testExpectOutputStringFooActualBar'); $result = $test->run(); $this->assertCount(1, $result); $this->assertFalse($result->wasSuccessful()); } public function testExpectOutputRegexFooActualFoo(): void { $test = new \OutputTestCase('testExpectOutputRegexFooActualFoo'); $result = $test->run(); $this->assertCount(1, $result); $this->assertTrue($result->wasSuccessful()); } public function testExpectOutputRegexFooActualBar(): void { $test = new \OutputTestCase('testExpectOutputRegexFooActualBar'); $result = $test->run(); $this->assertCount(1, $result); $this->assertFalse($result->wasSuccessful()); } public function testSkipsIfRequiresHigherVersionOfPHPUnit(): void { $test = new \RequirementsTest('testAlwaysSkip'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); $this->assertEquals( 'PHPUnit >= 1111111 is required.', $test->getStatusMessage() ); } public function testSkipsIfRequiresHigherVersionOfPHP(): void { $test = new \RequirementsTest('testAlwaysSkip2'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); $this->assertEquals( 'PHP >= 9999999 is required.', $test->getStatusMessage() ); } public function testSkipsIfRequiresNonExistingOs(): void { $test = new \RequirementsTest('testAlwaysSkip3'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); $this->assertEquals( 'Operating system matching /DOESNOTEXIST/i is required.', $test->getStatusMessage() ); } public function testSkipsIfRequiresNonExistingOsFamily(): void { $test = new \RequirementsTest('testAlwaysSkip4'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); $this->assertEquals( 'Operating system DOESNOTEXIST is required.', $test->getStatusMessage() ); } public function testSkipsIfRequiresNonExistingFunction(): void { $test = new \RequirementsTest('testNine'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); $this->assertEquals( 'Function testFunc is required.', $test->getStatusMessage() ); } public function testSkipsIfRequiresNonExistingExtension(): void { $test = new \RequirementsTest('testTen'); $test->run(); $this->assertEquals( 'Extension testExt is required.', $test->getStatusMessage() ); } public function testSkipsIfRequiresExtensionWithAMinimumVersion(): void { $test = new \RequirementsTest('testSpecificExtensionVersion'); $test->run(); $this->assertEquals( 'Extension testExt >= 1.8.0 is required.', $test->getStatusMessage() ); } public function testSkipsProvidesMessagesForAllSkippingReasons(): void { $test = new \RequirementsTest('testAllPossibleRequirements'); $test->run(); $this->assertEquals( 'PHP >= 99-dev is required.' . \PHP_EOL . 'PHPUnit >= 9-dev is required.' . \PHP_EOL . 'Operating system matching /DOESNOTEXIST/i is required.' . \PHP_EOL . 'Function testFuncOne is required.' . \PHP_EOL . 'Function testFunc2 is required.' . \PHP_EOL . 'Setting "not_a_setting" must be "Off".' . \PHP_EOL . 'Extension testExtOne is required.' . \PHP_EOL . 'Extension testExt2 is required.' . \PHP_EOL . 'Extension testExtThree >= 2.0 is required.', $test->getStatusMessage() ); } public function testRequiringAnExistingMethodDoesNotSkip(): void { $test = new \RequirementsTest('testExistingMethod'); $result = $test->run(); $this->assertEquals(0, $result->skippedCount()); } public function testRequiringAnExistingFunctionDoesNotSkip(): void { $test = new \RequirementsTest('testExistingFunction'); $result = $test->run(); $this->assertEquals(0, $result->skippedCount()); } public function testRequiringAnExistingExtensionDoesNotSkip(): void { $test = new \RequirementsTest('testExistingExtension'); $result = $test->run(); $this->assertEquals(0, $result->skippedCount()); } public function testRequiringAnExistingOsDoesNotSkip(): void { $test = new \RequirementsTest('testExistingOs'); $result = $test->run(); $this->assertEquals(0, $result->skippedCount()); } public function testRequiringASetting(): void { $test = new \RequirementsTest('testSettingDisplayErrorsOn'); // Get this so we can return it to whatever it was before the test. $displayErrorsVal = \ini_get('display_errors'); \ini_set('display_errors', 'On'); $result = $test->run(); $this->assertEquals(0, $result->skippedCount()); \ini_set('display_errors', 'Off'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); \ini_set('display_errors', $displayErrorsVal); } public function testCurrentWorkingDirectoryIsRestored(): void { $expectedCwd = \getcwd(); $test = new \ChangeCurrentWorkingDirectoryTest('testSomethingThatChangesTheCwd'); $test->run(); $this->assertSame($expectedCwd, \getcwd()); } /** * @requires PHP 7 */ public function testTypeErrorCanBeExpected(): void { $o = new \ClassWithScalarTypeDeclarations; $this->expectException(\TypeError::class); $o->foo(null, null); } public function testCreateMockFromClassName(): void { $mock = $this->createMock(\Mockable::class); $this->assertInstanceOf(\Mockable::class, $mock); $this->assertInstanceOf(MockObject::class, $mock); } public function testCreateMockMocksAllMethods(): void { $mock = $this->createMock(\Mockable::class); $this->assertNull($mock->mockableMethod()); $this->assertNull($mock->anotherMockableMethod()); } public function testCreateStubFromClassName(): void { $mock = $this->createStub(\Mockable::class); $this->assertInstanceOf(\Mockable::class, $mock); $this->assertInstanceOf(Stub::class, $mock); } public function testCreateStubStubsAllMethods(): void { $mock = $this->createStub(\Mockable::class); $this->assertNull($mock->mockableMethod()); $this->assertNull($mock->anotherMockableMethod()); } public function testCreatePartialMockDoesNotMockAllMethods(): void { /** @var \Mockable $mock */ $mock = $this->createPartialMock(\Mockable::class, ['mockableMethod']); $this->assertNull($mock->mockableMethod()); $this->assertTrue($mock->anotherMockableMethod()); } public function testCreatePartialMockCanMockNoMethods(): void { /** @var \Mockable $mock */ $mock = $this->createPartialMock(\Mockable::class, []); $this->assertTrue($mock->mockableMethod()); $this->assertTrue($mock->anotherMockableMethod()); } public function testCreatePartialMockWithFakeMethods(): void { $test = new \TestWithDifferentStatuses('testWithCreatePartialMockWarning'); $test->run(); $this->assertSame(BaseTestRunner::STATUS_WARNING, $test->getStatus()); $this->assertFalse($test->hasFailed()); } public function testCreatePartialMockWithRealMethods(): void { $test = new \TestWithDifferentStatuses('testWithCreatePartialMockPassesNoWarning'); $test->run(); $this->assertSame(BaseTestRunner::STATUS_PASSED, $test->getStatus()); $this->assertFalse($test->hasFailed()); } public function testCreateMockSkipsConstructor(): void { $mock = $this->createMock(\Mockable::class); $this->assertNull($mock->constructorArgs); } public function testCreateMockDisablesOriginalClone(): void { $mock = $this->createMock(\Mockable::class); $cloned = clone $mock; $this->assertNull($cloned->cloned); } public function testCreateStubSkipsConstructor(): void { $mock = $this->createStub(\Mockable::class); $this->assertNull($mock->constructorArgs); } public function testCreateStubDisablesOriginalClone(): void { $mock = $this->createStub(\Mockable::class); $cloned = clone $mock; $this->assertNull($cloned->cloned); } public function testConfiguredMockCanBeCreated(): void { /** @var \Mockable $mock */ $mock = $this->createConfiguredMock( \Mockable::class, [ 'mockableMethod' => false, ] ); $this->assertFalse($mock->mockableMethod()); $this->assertNull($mock->anotherMockableMethod()); } public function testProvidingOfAutoreferencedArray(): void { $test = new \TestAutoreferenced('testJsonEncodeException', $this->getAutoreferencedArray()); $test->runBare(); $this->assertIsArray($test->myTestData); $this->assertArrayHasKey('data', $test->myTestData); $this->assertEquals($test->myTestData['data'][0], $test->myTestData['data']); } public function testProvidingArrayThatMixesObjectsAndScalars(): void { $data = [ [123], ['foo'], [$this->createMock(\Mockable::class)], [$this->createStub(\Mockable::class)], ]; $test = new \TestAutoreferenced('testJsonEncodeException', [$data]); $test->runBare(); $this->assertIsArray($test->myTestData); $this->assertSame($data, $test->myTestData); } public function testGettingNullTestResultObject(): void { $test = new \Success; $this->assertNull($test->getTestResultObject()); } public function testSizeUnknown(): void { $test = new \TestWithDifferentSizes('testWithSizeUnknown'); $this->assertFalse($test->hasSize()); $this->assertSame(TestUtil::UNKNOWN, $test->getSize()); $this->assertFalse($test->isLarge()); $this->assertFalse($test->isMedium()); $this->assertFalse($test->isSmall()); } public function testSizeLarge(): void { $test = new \TestWithDifferentSizes('testWithSizeLarge'); $this->assertTrue($test->hasSize()); $this->assertSame(TestUtil::LARGE, $test->getSize()); $this->assertTrue($test->isLarge()); $this->assertFalse($test->isMedium()); $this->assertFalse($test->isSmall()); } public function testSizeMedium(): void { $test = new \TestWithDifferentSizes('testWithSizeMedium'); $this->assertTrue($test->hasSize()); $this->assertSame(TestUtil::MEDIUM, $test->getSize()); $this->assertFalse($test->isLarge()); $this->assertTrue($test->isMedium()); $this->assertFalse($test->isSmall()); } public function testSizeSmall(): void { $test = new \TestWithDifferentSizes('testWithSizeSmall'); $this->assertTrue($test->hasSize()); $this->assertSame(TestUtil::SMALL, $test->getSize()); $this->assertFalse($test->isLarge()); $this->assertFalse($test->isMedium()); $this->assertTrue($test->isSmall()); } public function testGetNameReturnsMethodName(): void { $methodName = 'testWithName'; $testCase = new \TestWithDifferentNames($methodName); $this->assertSame($methodName, $testCase->getName()); } public function testGetNameReturnsEmptyStringAsDefault(): void { $testCase = new \TestWithDifferentNames(); $this->assertSame('', $testCase->getName()); } /** * @dataProvider providerInvalidName */ public function testRunBareThrowsExceptionWhenTestHasInvalidName($name): void { $testCase = new \TestWithDifferentNames($name); $this->expectException(Exception::class); $this->expectExceptionMessage('PHPUnit\Framework\TestCase::$name must be a non-blank string.'); $testCase->runBare(); } public function providerInvalidName(): array { return [ 'null' => [null], 'string-empty' => [''], 'string-blank' => [' '], ]; } public function testHasFailedReturnsFalseWhenTestHasNotRunYet(): void { $test = new \TestWithDifferentStatuses(); $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $test->getStatus()); $this->assertFalse($test->hasFailed()); } public function testHasFailedReturnsTrueWhenTestHasFailed(): void { $test = new \TestWithDifferentStatuses('testThatFails'); $test->run(); $this->assertSame(BaseTestRunner::STATUS_FAILURE, $test->getStatus()); $this->assertTrue($test->hasFailed()); } public function testHasFailedReturnsTrueWhenTestHasErrored(): void { $test = new \TestWithDifferentStatuses('testThatErrors'); $test->run(); $this->assertSame(BaseTestRunner::STATUS_ERROR, $test->getStatus()); $this->assertTrue($test->hasFailed()); } public function testHasFailedReturnsFalseWhenTestHasPassed(): void { $test = new \TestWithDifferentStatuses('testThatPasses'); $test->run(); $this->assertSame(BaseTestRunner::STATUS_PASSED, $test->getStatus()); $this->assertFalse($test->hasFailed()); } public function testHasFailedReturnsFalseWhenTestHasBeenMarkedAsIncomplete(): void { $test = new \TestWithDifferentStatuses('testThatIsMarkedAsIncomplete'); $test->run(); $this->assertSame(BaseTestRunner::STATUS_INCOMPLETE, $test->getStatus()); $this->assertFalse($test->hasFailed()); } public function testHasFailedReturnsFalseWhenTestHasBeenMarkedAsRisky(): void { $test = new \TestWithDifferentStatuses('testThatIsMarkedAsRisky'); $test->run(); $this->assertSame(BaseTestRunner::STATUS_RISKY, $test->getStatus()); $this->assertFalse($test->hasFailed()); } public function testHasFailedReturnsFalseWhenTestHasBeenMarkedAsSkipped(): void { $test = new \TestWithDifferentStatuses('testThatIsMarkedAsSkipped'); $test->run(); $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $test->getStatus()); $this->assertFalse($test->hasFailed()); } public function testHasFailedReturnsFalseWhenTestHasEmittedWarning(): void { $test = new \TestWithDifferentStatuses('testThatAddsAWarning'); $test->run(); $this->assertSame(BaseTestRunner::STATUS_WARNING, $test->getStatus()); $this->assertFalse($test->hasFailed()); } public function testHasOutputReturnsFalseWhenTestDoesNotGenerateOutput(): void { $test = new \TestWithDifferentOutput('testThatDoesNotGenerateOutput'); $test->run(); $this->assertFalse($test->hasOutput()); } public function testHasOutputReturnsFalseWhenTestExpectsOutputRegex(): void { $test = new \TestWithDifferentOutput('testThatExpectsOutputRegex'); $test->run(); $this->assertFalse($test->hasOutput()); } public function testHasOutputReturnsFalseWhenTestExpectsOutputString(): void { $test = new \TestWithDifferentOutput('testThatExpectsOutputString'); $test->run(); $this->assertFalse($test->hasOutput()); } public function testHasOutputReturnsTrueWhenTestGeneratesOutput(): void { $test = new \TestWithDifferentOutput('testThatGeneratesOutput'); $test->run(); $this->assertTrue($test->hasOutput()); } public function testDeprecationCanBeExpected(): void { $this->expectDeprecation(); $this->expectDeprecationMessage('foo'); $this->expectDeprecationMessageMatches('/foo/'); \trigger_error('foo', \E_USER_DEPRECATED); } public function testNoticeCanBeExpected(): void { $this->expectNotice(); $this->expectNoticeMessage('foo'); $this->expectNoticeMessageMatches('/foo/'); \trigger_error('foo', \E_USER_NOTICE); } public function testWarningCanBeExpected(): void { $this->expectWarning(); $this->expectWarningMessage('foo'); $this->expectWarningMessageMatches('/foo/'); \trigger_error('foo', \E_USER_WARNING); } public function testErrorCanBeExpected(): void { $this->expectError(); $this->expectErrorMessage('foo'); $this->expectErrorMessageMatches('/foo/'); \trigger_error('foo', \E_USER_ERROR); } /** * @return array */ private function getAutoreferencedArray() { $recursionData = []; $recursionData[] = &$recursionData; return [ 'RECURSION' => [ 'data' => $recursionData, ], ]; } } PK!D'Framework/MockObject/MockObjectTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** * @small */ final class MockObjectTest extends TestCase { public function testMockedMethodIsNeverCalled(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->never()) ->method('doSomething'); } public function testMockedMethodIsNeverCalledWithParameter(): void { $mock = $this->getMockBuilder(SomeClass::class) ->getMock(); $mock->expects($this->never()) ->method('doSomething') ->with('someArg'); } /** * @doesNotPerformAssertions */ public function testMockedMethodIsNotCalledWhenExpectsAnyWithParameter(): void { $mock = $this->getMockBuilder(SomeClass::class) ->getMock(); $mock->expects($this->any()) ->method('doSomethingElse') ->with('someArg'); } /** * @doesNotPerformAssertions */ public function testMockedMethodIsNotCalledWhenMethodSpecifiedDirectlyWithParameter(): void { $mock = $this->getMockBuilder(SomeClass::class) ->getMock(); $mock->method('doSomethingElse') ->with('someArg'); } public function testMockedMethodIsCalledAtLeastOnce(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->atLeastOnce()) ->method('doSomething'); $mock->doSomething(); } public function testMockedMethodIsCalledAtLeastOnce2(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->atLeastOnce()) ->method('doSomething'); $mock->doSomething(); $mock->doSomething(); } public function testMockedMethodIsCalledAtLeastTwice(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->atLeast(2)) ->method('doSomething'); $mock->doSomething(); $mock->doSomething(); } public function testMockedMethodIsCalledAtLeastTwice2(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->atLeast(2)) ->method('doSomething'); $mock->doSomething(); $mock->doSomething(); $mock->doSomething(); } public function testMockedMethodIsCalledAtMostTwice(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->atMost(2)) ->method('doSomething'); $mock->doSomething(); $mock->doSomething(); } public function testMockedMethodIsCalledAtMosttTwice2(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->atMost(2)) ->method('doSomething'); $mock->doSomething(); } public function testMockedMethodIsCalledOnce(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->once()) ->method('doSomething'); $mock->doSomething(); } public function testMockedMethodIsCalledOnceWithParameter(): void { $mock = $this->getMockBuilder(SomeClass::class) ->getMock(); $mock->expects($this->once()) ->method('doSomethingElse') ->with($this->equalTo('something')); $mock->doSomethingElse('something'); } public function testMockedMethodIsCalledExactly(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->exactly(2)) ->method('doSomething'); $mock->doSomething(); $mock->doSomething(); } public function testStubbedException(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->will($this->throwException(new \Exception)); $this->expectException(\Exception::class); $mock->doSomething(); } public function testStubbedWillThrowException(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->willThrowException(new \Exception); $this->expectException(\Exception::class); $mock->doSomething(); } public function testStubbedReturnValue(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->will($this->returnValue('something')); $this->assertEquals('something', $mock->doSomething()); $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->willReturn('something'); $this->assertEquals('something', $mock->doSomething()); } public function testStubbedReturnValueMap(): void { $map = [ ['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ]; $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->will($this->returnValueMap($map)); $this->assertEquals('d', $mock->doSomething('a', 'b', 'c')); $this->assertEquals('h', $mock->doSomething('e', 'f', 'g')); $this->assertNull($mock->doSomething('foo', 'bar')); $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->willReturnMap($map); $this->assertEquals('d', $mock->doSomething('a', 'b', 'c')); $this->assertEquals('h', $mock->doSomething('e', 'f', 'g')); $this->assertNull($mock->doSomething('foo', 'bar')); } public function testStubbedReturnArgument(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->will($this->returnArgument(1)); $this->assertEquals('b', $mock->doSomething('a', 'b')); $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->willReturnArgument(1); $this->assertEquals('b', $mock->doSomething('a', 'b')); } public function testFunctionCallback(): void { $mock = $this->getMockBuilder(SomeClass::class) ->setMethods(['doSomething']) ->getMock(); $mock->expects($this->once()) ->method('doSomething') ->will($this->returnCallback('FunctionCallbackWrapper::functionCallback')); $this->assertEquals('pass', $mock->doSomething('foo', 'bar')); $mock = $this->getMockBuilder(SomeClass::class) ->setMethods(['doSomething']) ->getMock(); $mock->expects($this->once()) ->method('doSomething') ->willReturnCallback('FunctionCallbackWrapper::functionCallback'); $this->assertEquals('pass', $mock->doSomething('foo', 'bar')); } public function testStubbedReturnSelf(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->will($this->returnSelf()); $this->assertEquals($mock, $mock->doSomething()); $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->willReturnSelf(); $this->assertEquals($mock, $mock->doSomething()); } public function testStubbedReturnOnConsecutiveCalls(): void { $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->will($this->onConsecutiveCalls('a', 'b', 'c')); $this->assertEquals('a', $mock->doSomething()); $this->assertEquals('b', $mock->doSomething()); $this->assertEquals('c', $mock->doSomething()); $mock = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock->expects($this->any()) ->method('doSomething') ->willReturnOnConsecutiveCalls('a', 'b', 'c'); $this->assertEquals('a', $mock->doSomething()); $this->assertEquals('b', $mock->doSomething()); $this->assertEquals('c', $mock->doSomething()); } public function testStaticMethodCallback(): void { $mock = $this->getMockBuilder(SomeClass::class) ->setMethods(['doSomething']) ->getMock(); $mock->expects($this->once()) ->method('doSomething') ->will($this->returnCallback(['MethodCallback', 'staticCallback'])); $this->assertEquals('pass', $mock->doSomething('foo', 'bar')); } public function testPublicMethodCallback(): void { $mock = $this->getMockBuilder(SomeClass::class) ->setMethods(['doSomething']) ->getMock(); $mock->expects($this->once()) ->method('doSomething') ->will($this->returnCallback([new MethodCallback, 'nonStaticCallback'])); $this->assertEquals('pass', $mock->doSomething('foo', 'bar')); } public function testMockClassOnlyGeneratedOnce(): void { $mock1 = $this->getMockBuilder(AnInterface::class) ->getMock(); $mock2 = $this->getMockBuilder(AnInterface::class) ->getMock(); $this->assertEquals(\get_class($mock1), \get_class($mock2)); } public function testMockClassDifferentForPartialMocks(): void { $mock1 = $this->getMockBuilder(PartialMockTestClass::class) ->getMock(); $mock2 = $this->getMockBuilder(PartialMockTestClass::class) ->setMethods(['doSomething']) ->getMock(); $mock3 = $this->getMockBuilder(PartialMockTestClass::class) ->setMethods(['doSomething']) ->getMock(); $mock4 = $this->getMockBuilder(PartialMockTestClass::class) ->setMethods(['doAnotherThing']) ->getMock(); $mock5 = $this->getMockBuilder(PartialMockTestClass::class) ->setMethods(['doAnotherThing']) ->getMock(); $this->assertNotEquals(\get_class($mock1), \get_class($mock2)); $this->assertNotEquals(\get_class($mock1), \get_class($mock3)); $this->assertNotEquals(\get_class($mock1), \get_class($mock4)); $this->assertNotEquals(\get_class($mock1), \get_class($mock5)); $this->assertEquals(\get_class($mock2), \get_class($mock3)); $this->assertNotEquals(\get_class($mock2), \get_class($mock4)); $this->assertNotEquals(\get_class($mock2), \get_class($mock5)); $this->assertEquals(\get_class($mock4), \get_class($mock5)); } public function testMockClassStoreOverrulable(): void { $mock1 = $this->getMockBuilder(PartialMockTestClass::class) ->getMock(); $mock2 = $this->getMockBuilder(PartialMockTestClass::class) ->setMockClassName('MyMockClassNameForPartialMockTestClass1') ->getMock(); $mock3 = $this->getMockBuilder(PartialMockTestClass::class) ->getMock(); $mock4 = $this->getMockBuilder(PartialMockTestClass::class) ->setMethods(['doSomething']) ->setMockClassName('AnotherMockClassNameForPartialMockTestClass') ->getMock(); $mock5 = $this->getMockBuilder(PartialMockTestClass::class) ->setMockClassName('MyMockClassNameForPartialMockTestClass2') ->getMock(); $this->assertNotEquals(\get_class($mock1), \get_class($mock2)); $this->assertEquals(\get_class($mock1), \get_class($mock3)); $this->assertNotEquals(\get_class($mock1), \get_class($mock4)); $this->assertNotEquals(\get_class($mock2), \get_class($mock3)); $this->assertNotEquals(\get_class($mock2), \get_class($mock4)); $this->assertNotEquals(\get_class($mock2), \get_class($mock5)); $this->assertNotEquals(\get_class($mock3), \get_class($mock4)); $this->assertNotEquals(\get_class($mock3), \get_class($mock5)); $this->assertNotEquals(\get_class($mock4), \get_class($mock5)); } public function testGetMockWithFixedClassNameCanProduceTheSameMockTwice(): void { $mock = $this->getMockBuilder(stdClass::class)->setMockClassName('FixedName')->getMock(); $this->assertInstanceOf(stdClass::class, $mock); } public function testOriginalConstructorSettingConsidered(): void { $mock1 = $this->getMockBuilder(PartialMockTestClass::class) ->getMock(); $mock2 = $this->getMockBuilder(PartialMockTestClass::class) ->disableOriginalConstructor() ->getMock(); $this->assertTrue($mock1->constructorCalled); $this->assertFalse($mock2->constructorCalled); } public function testOriginalCloneSettingConsidered(): void { $mock1 = $this->getMockBuilder(PartialMockTestClass::class) ->getMock(); $mock2 = $this->getMockBuilder(PartialMockTestClass::class) ->disableOriginalClone() ->getMock(); $this->assertNotEquals(\get_class($mock1), \get_class($mock2)); } /** * @testdox getMock() for abstract class */ public function testGetMockForAbstractClass(): void { $mock = $this->getMockBuilder(AbstractMockTestClass::class) ->getMock(); $mock->expects($this->never()) ->method('doSomething'); } /** * @testdox getMock() for Traversable $_dataName * @dataProvider traversableProvider */ public function testGetMockForTraversable($type): void { $mock = $this->getMockBuilder($type) ->getMock(); $this->assertInstanceOf(Traversable::class, $mock); } /** * @testdox getMockForTrait() */ public function testGetMockForTrait(): void { $mock = $this->getMockForTrait(AbstractTrait::class); $mock->expects($this->never()) ->method('doSomething'); $parent = \get_parent_class($mock); $traits = \class_uses($parent, false); $this->assertContains(AbstractTrait::class, $traits); } public function testClonedMockObjectShouldStillEqualTheOriginal(): void { $a = $this->getMockBuilder(stdClass::class) ->getMock(); $b = clone $a; $this->assertEquals($a, $b); } public function testMockObjectsConstructedIndepentantlyShouldBeEqual(): void { $a = $this->getMockBuilder(stdClass::class) ->getMock(); $b = $this->getMockBuilder(stdClass::class) ->getMock(); $this->assertEquals($a, $b); } public function testMockObjectsConstructedIndepentantlyShouldNotBeTheSame(): void { $a = $this->getMockBuilder(stdClass::class) ->getMock(); $b = $this->getMockBuilder(stdClass::class) ->getMock(); $this->assertNotSame($a, $b); } public function testClonedMockObjectCanBeUsedInPlaceOfOriginalOne(): void { $x = $this->getMockBuilder(stdClass::class) ->getMock(); $y = clone $x; $mock = $this->getMockBuilder(stdClass::class) ->setMethods(['foo']) ->getMock(); $mock->expects($this->once()) ->method('foo') ->with($this->equalTo($x)); $mock->foo($y); } public function testClonedMockObjectIsNotIdenticalToOriginalOne(): void { $x = $this->getMockBuilder(stdClass::class) ->getMock(); $y = clone $x; $mock = $this->getMockBuilder(stdClass::class) ->setMethods(['foo']) ->getMock(); $mock->expects($this->once()) ->method('foo') ->with($this->logicalNot($this->identicalTo($x))); $mock->foo($y); } public function testObjectMethodCallWithArgumentCloningEnabled(): void { $expectedObject = new stdClass; $mock = $this->getMockBuilder('SomeClass') ->setMethods(['doSomethingElse']) ->enableArgumentCloning() ->getMock(); $actualArguments = []; $mock->expects($this->any()) ->method('doSomethingElse') ->will( $this->returnCallback( function () use (&$actualArguments): void { $actualArguments = \func_get_args(); } ) ); $mock->doSomethingElse($expectedObject); $this->assertCount(1, $actualArguments); $this->assertEquals($expectedObject, $actualArguments[0]); $this->assertNotSame($expectedObject, $actualArguments[0]); } public function testObjectMethodCallWithArgumentCloningDisabled(): void { $expectedObject = new stdClass; $mock = $this->getMockBuilder('SomeClass') ->setMethods(['doSomethingElse']) ->disableArgumentCloning() ->getMock(); $actualArguments = []; $mock->expects($this->any()) ->method('doSomethingElse') ->will( $this->returnCallback( function () use (&$actualArguments): void { $actualArguments = \func_get_args(); } ) ); $mock->doSomethingElse($expectedObject); $this->assertCount(1, $actualArguments); $this->assertSame($expectedObject, $actualArguments[0]); } public function testArgumentCloningOptionGeneratesUniqueMock(): void { $mockWithCloning = $this->getMockBuilder('SomeClass') ->setMethods(['doSomethingElse']) ->enableArgumentCloning() ->getMock(); $mockWithoutCloning = $this->getMockBuilder('SomeClass') ->setMethods(['doSomethingElse']) ->disableArgumentCloning() ->getMock(); $this->assertNotEquals($mockWithCloning, $mockWithoutCloning); } public function testVerificationOfMethodNameFailsWithoutParameters(): void { $mock = $this->getMockBuilder(SomeClass::class) ->setMethods(['right', 'wrong']) ->getMock(); $mock->expects($this->once()) ->method('right'); $mock->wrong(); try { $mock->__phpunit_verify(); $this->fail('Expected exception'); } catch (ExpectationFailedException $e) { $this->assertSame( "Expectation failed for method name is \"right\" when invoked 1 time(s).\n" . 'Method was expected to be called 1 times, actually called 0 times.' . "\n", $e->getMessage() ); } $this->resetMockObjects(); } public function testVerificationOfMethodNameFailsWithParameters(): void { $mock = $this->getMockBuilder(SomeClass::class) ->setMethods(['right', 'wrong']) ->getMock(); $mock->expects($this->once()) ->method('right'); $mock->wrong(); try { $mock->__phpunit_verify(); $this->fail('Expected exception'); } catch (ExpectationFailedException $e) { $this->assertSame( "Expectation failed for method name is \"right\" when invoked 1 time(s).\n" . 'Method was expected to be called 1 times, actually called 0 times.' . "\n", $e->getMessage() ); } $this->resetMockObjects(); } public function testVerificationOfMethodNameFailsWithWrongParameters(): void { $mock = $this->getMockBuilder(SomeClass::class) ->setMethods(['right', 'wrong']) ->getMock(); $mock->expects($this->once()) ->method('right') ->with(['first', 'second']); try { $mock->right(['second']); } catch (ExpectationFailedException $e) { $this->assertSame( "Expectation failed for method name is \"right\" when invoked 1 time(s)\n" . 'Parameter 0 for invocation SomeClass::right(Array (...)) does not match expected value.' . "\n" . 'Failed asserting that two arrays are equal.', $e->getMessage() ); } try { $mock->__phpunit_verify(); // CHECKOUT THIS MORE CAREFULLY // $this->fail('Expected exception'); } catch (ExpectationFailedException $e) { $this->assertSame( "Expectation failed for method name is \"right\" when invoked 1 time(s).\n" . 'Parameter 0 for invocation SomeClass::right(Array (...)) does not match expected value.' . "\n" . 'Failed asserting that two arrays are equal.' . "\n" . '--- Expected' . "\n" . '+++ Actual' . "\n" . '@@ @@' . "\n" . ' Array (' . "\n" . '- 0 => \'first\'' . "\n" . '- 1 => \'second\'' . "\n" . '+ 0 => \'second\'' . "\n" . ' )' . "\n", $e->getMessage() ); } $this->resetMockObjects(); } public function testVerificationOfNeverFailsWithEmptyParameters(): void { $mock = $this->getMockBuilder(SomeClass::class) ->setMethods(['right', 'wrong']) ->getMock(); $mock->expects($this->never()) ->method('right') ->with(); try { $mock->right(); $this->fail('Expected exception'); } catch (ExpectationFailedException $e) { $this->assertSame( 'SomeClass::right() was not expected to be called.', $e->getMessage() ); } $this->resetMockObjects(); } public function testVerificationOfNeverFailsWithAnyParameters(): void { $mock = $this->getMockBuilder(SomeClass::class) ->setMethods(['right', 'wrong']) ->getMock(); $mock->expects($this->never()) ->method('right') ->withAnyParameters(); try { $mock->right(); $this->fail('Expected exception'); } catch (ExpectationFailedException $e) { $this->assertSame( 'SomeClass::right() was not expected to be called.', $e->getMessage() ); } $this->resetMockObjects(); } public function testWithAnythingInsteadOfWithAnyParameters(): void { $mock = $this->getMockBuilder(SomeClass::class) ->setMethods(['right', 'wrong']) ->getMock(); $mock->expects($this->once()) ->method('right') ->with($this->anything()); try { $mock->right(); $this->fail('Expected exception'); } catch (ExpectationFailedException $e) { $this->assertSame( "Expectation failed for method name is \"right\" when invoked 1 time(s)\n" . 'Parameter count for invocation SomeClass::right() is too low.' . "\n" . 'To allow 0 or more parameters with any value, omit ->with() or use ->withAnyParameters() instead.', $e->getMessage() ); } $this->resetMockObjects(); } /** * See https://github.com/sebastianbergmann/phpunit-mock-objects/issues/81 */ public function testMockArgumentsPassedByReference(): void { $foo = $this->getMockBuilder('MethodCallbackByReference') ->setMethods(['bar']) ->disableOriginalConstructor() ->disableArgumentCloning() ->getMock(); $foo->expects($this->any()) ->method('bar') ->will($this->returnCallback([$foo, 'callback'])); $a = $b = $c = 0; $foo->bar($a, $b, $c); $this->assertEquals(1, $b); } /** * See https://github.com/sebastianbergmann/phpunit-mock-objects/issues/81 */ public function testMockArgumentsPassedByReference2(): void { $foo = $this->getMockBuilder('MethodCallbackByReference') ->disableOriginalConstructor() ->disableArgumentCloning() ->getMock(); $foo->expects($this->any()) ->method('bar') ->will($this->returnCallback( function (&$a, &$b, $c): void { $b = 1; } )); $a = $b = $c = 0; $foo->bar($a, $b, $c); $this->assertEquals(1, $b); } /** * @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/116 */ public function testMockArgumentsPassedByReference3(): void { $foo = $this->getMockBuilder('MethodCallbackByReference') ->setMethods(['bar']) ->disableOriginalConstructor() ->disableArgumentCloning() ->getMock(); $a = new stdClass; $b = $c = 0; $foo->expects($this->any()) ->method('bar') ->with($a, $b, $c) ->will($this->returnCallback([$foo, 'callback'])); $this->assertNull($foo->bar($a, $b, $c)); } /** * @see https://github.com/sebastianbergmann/phpunit/issues/796 */ public function testMockArgumentsPassedByReference4(): void { $foo = $this->getMockBuilder('MethodCallbackByReference') ->setMethods(['bar']) ->disableOriginalConstructor() ->disableArgumentCloning() ->getMock(); $a = new stdClass; $b = $c = 0; $foo->expects($this->any()) ->method('bar') ->with($this->isInstanceOf(stdClass::class), $b, $c) ->will($this->returnCallback([$foo, 'callback'])); $this->assertNull($foo->bar($a, $b, $c)); } /** * @requires extension soap */ public function testCreateMockFromWsdl(): void { $mock = $this->getMockFromWsdl(TEST_FILES_PATH . 'GoogleSearch.wsdl', 'WsdlMock'); $this->assertStringStartsWith( 'Mock_WsdlMock_', \get_class($mock) ); } /** * @requires extension soap */ public function testCreateNamespacedMockFromWsdl(): void { $mock = $this->getMockFromWsdl(TEST_FILES_PATH . 'GoogleSearch.wsdl', 'My\\Space\\WsdlMock'); $this->assertStringStartsWith( 'Mock_WsdlMock_', \get_class($mock) ); } /** * @requires extension soap */ public function testCreateTwoMocksOfOneWsdlFile(): void { $a = $this->getMockFromWsdl(TEST_FILES_PATH . 'GoogleSearch.wsdl'); $b = $this->getMockFromWsdl(TEST_FILES_PATH . 'GoogleSearch.wsdl'); $this->assertStringStartsWith('Mock_GoogleSearch_', \get_class($a)); $this->assertEquals(\get_class($a), \get_class($b)); } /** * @see https://github.com/sebastianbergmann/phpunit/issues/2573 * @ticket 2573 * @requires extension soap */ public function testCreateMockOfWsdlFileWithSpecialChars(): void { $mock = $this->getMockFromWsdl(TEST_FILES_PATH . 'Go ogle-Sea.rch.wsdl'); $this->assertStringStartsWith('Mock_GoogleSearch_', \get_class($mock)); } /** * @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/156 * @ticket 156 */ public function testInterfaceWithStaticMethodCanBeStubbed(): void { $this->assertInstanceOf( InterfaceWithStaticMethod::class, $this->getMockBuilder(InterfaceWithStaticMethod::class)->getMock() ); } public function testInvokingStubbedStaticMethodRaisesException(): void { $mock = $this->getMockBuilder(ClassWithStaticMethod::class)->getMock(); $this->expectException(\PHPUnit\Framework\MockObject\BadMethodCallException::class); $mock->staticMethod(); } /** * @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/171 * @ticket 171 */ public function testStubForClassThatImplementsSerializableCanBeCreatedWithoutInvokingTheConstructor(): void { $this->assertInstanceOf( ClassThatImplementsSerializable::class, $this->getMockBuilder(ClassThatImplementsSerializable::class) ->disableOriginalConstructor() ->getMock() ); } public function testGetMockForClassWithSelfTypeHint(): void { $this->assertInstanceOf( ClassWithSelfTypeHint::class, $this->getMockBuilder(ClassWithSelfTypeHint::class)->getMock() ); } public function testStringableClassDoesNotThrow(): void { /** @var PHPUnit\Framework\MockObject\MockObject|StringableClass $mock */ $mock = $this->getMockBuilder(StringableClass::class)->getMock(); $this->assertIsString((string) $mock); } public function testStringableClassCanBeMocked(): void { /** @var PHPUnit\Framework\MockObject\MockObject|StringableClass $mock */ $mock = $this->getMockBuilder(StringableClass::class)->getMock(); $mock->method('__toString')->willReturn('foo'); $this->assertSame('foo', (string) $mock); } public function traversableProvider(): array { return [ 'Traversable' => ['Traversable'], '\Traversable' => ['\Traversable'], 'TraversableMockTestInterface' => ['TraversableMockTestInterface'], ]; } public function testParameterCallbackConstraintOnlyEvaluatedOnce(): void { $mock = $this->getMockBuilder(Foo::class)->setMethods(['bar'])->getMock(); $expectedNumberOfCalls = 1; $callCount = 0; $mock->expects($this->exactly($expectedNumberOfCalls))->method('bar') ->with($this->callback(function ($argument) use (&$callCount) { return $argument === 'call_' . $callCount++; })); for ($i = 0; $i < $expectedNumberOfCalls; $i++) { $mock->bar('call_' . $i); } } public function testReturnTypesAreMockedCorrectly(): void { /** @var ClassWithAllPossibleReturnTypes|MockObject $stub */ $stub = $this->createMock(ClassWithAllPossibleReturnTypes::class); $this->assertNull($stub->methodWithNoReturnTypeDeclaration()); $this->assertSame('', $stub->methodWithStringReturnTypeDeclaration()); $this->assertSame(0.0, $stub->methodWithFloatReturnTypeDeclaration()); $this->assertSame(0, $stub->methodWithIntReturnTypeDeclaration()); $this->assertFalse($stub->methodWithBoolReturnTypeDeclaration()); $this->assertSame([], $stub->methodWithArrayReturnTypeDeclaration()); $this->assertInstanceOf(MockObject::class, $stub->methodWithClassReturnTypeDeclaration()); } public function testDisableAutomaticReturnValueGeneration(): void { $mock = $this->getMockBuilder(SomeClass::class) ->disableAutoReturnValueGeneration() ->getMock(); $this->expectException(ExpectationFailedException::class); $this->expectExceptionMessage( 'Return value inference disabled and no expectation set up for SomeClass::doSomethingElse()' ); $mock->doSomethingElse(1); } public function testDisableAutomaticReturnValueGenerationWithToString(): void { /** @var PHPUnit\Framework\MockObject\MockObject|StringableClass $mock */ $mock = $this->getMockBuilder(StringableClass::class) ->disableAutoReturnValueGeneration() ->getMock(); (string) $mock; try { $mock->__phpunit_verify(); $this->fail('Exception expected'); } catch (ExpectationFailedException $e) { $this->assertSame( 'Return value inference disabled and no expectation set up for StringableClass::__toString()', $e->getMessage() ); } $this->resetMockObjects(); } public function testVoidReturnTypeIsMockedCorrectly(): void { /** @var ClassWithAllPossibleReturnTypes|MockObject $stub */ $stub = $this->createMock(ClassWithAllPossibleReturnTypes::class); $this->assertNull($stub->methodWithVoidReturnTypeDeclaration()); } /** * @requires PHP 7.2 */ public function testObjectReturnTypeIsMockedCorrectly(): void { /** @var ClassWithAllPossibleReturnTypes|MockObject $stub */ $stub = $this->createMock(ClassWithAllPossibleReturnTypes::class); $this->assertInstanceOf(stdClass::class, $stub->methodWithObjectReturnTypeDeclaration()); } public function testTraitCanBeDoubled(): void { $object = $this->getObjectForTrait(ExampleTrait::class); $this->assertSame('ohHai', $object->ohHai()); } public function testTraitWithConstructorCanBeDoubled(): void { $object = $this->getObjectForTrait(TraitWithConstructor::class, ['value']); $this->assertSame('value', $object->value()); } private function resetMockObjects(): void { $refl = new ReflectionObject($this); $refl = $refl->getParentClass(); $prop = $refl->getProperty('mockObjects'); $prop->setAccessible(true); $prop->setValue($this, []); } } PK!f&Framework/MockObject/MockTraitTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\TestCase; final class MockTraitTest extends TestCase { public function testGenerateClassFromSource(): void { $mockName = 'PHPUnit\TestFixture\MockObject\MockTraitGenerated'; $file = __DIR__ . '/../../../_files/mock-object/MockTraitGenerated.tpl'; $mockTrait = new MockTrait(\file_get_contents($file), $mockName); $mockTrait->generate(); $this->assertTrue(\trait_exists($mockName)); } public function testGenerateReturnsNameOfGeneratedClass(): void { $mockName = 'PHPUnit\TestFixture\MockObject\MockTraitGenerated'; $mockTrait = new MockTrait('', $mockName); $this->assertEquals($mockName, $mockTrait->generate()); } } PK!&Framework/MockObject/MockClassTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\TestCase; use PHPUnit\TestFixture\MockObject\MockClassWithConfigurableMethods; use SebastianBergmann\Type\Type; final class MockClassTest extends TestCase { public function testGenerateClassFromSource(): void { $mockName = 'PHPUnit\TestFixture\MockObject\MockClassGenerated'; $file = __DIR__ . '/../../../_files/mock-object/MockClassGenerated.tpl'; $mockClass = new MockClass(\file_get_contents($file), $mockName, []); $mockClass->generate(); $this->assertTrue(\class_exists($mockName)); } public function testGenerateReturnsNameOfGeneratedClass(): void { $mockName = 'PHPUnit\TestFixture\MockObject\MockClassGenerated'; $mockClass = new MockClass('', $mockName, []); $this->assertEquals($mockName, $mockClass->generate()); } public function testConfigurableMethodsAreInitalized(): void { $configurableMethods = [new ConfigurableMethod('foo', Type::fromName('void', false))]; $mockClass = new MockClass('', MockClassWithConfigurableMethods::class, $configurableMethods); $mockClass->generate(); $this->assertSame($configurableMethods, MockClassWithConfigurableMethods::getConfigurableMethods()); } } PK!7K##5Framework/MockObject/Builder/InvocationMockerTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use PHPUnit\Framework\Constraint\IsEqual; use PHPUnit\Framework\MockObject\Builder\InvocationMocker; use PHPUnit\Framework\MockObject\IncompatibleReturnValueException; use PHPUnit\Framework\MockObject\InvocationHandler; use PHPUnit\Framework\MockObject\Matcher; use PHPUnit\Framework\MockObject\Stub\ReturnSelf; use PHPUnit\Framework\MockObject\Stub\ReturnStub; use PHPUnit\Framework\TestCase; use PHPUnit\TestFixture\MockObject\ClassWithImplicitProtocol; /** * @covers \PHPUnit\Framework\MockObject\Builder\InvocationMocker * @small */ final class InvocationMockerTest extends TestCase { public function testWillReturnWithOneValue(): void { $mock = $this->getMockBuilder(stdClass::class) ->setMethods(['foo']) ->getMock(); $mock->expects($this->any()) ->method('foo') ->willReturn(1); $this->assertEquals(1, $mock->foo()); } public function testWillReturnWithMultipleValues(): void { $mock = $this->getMockBuilder(stdClass::class) ->setMethods(['foo']) ->getMock(); $mock->expects($this->any()) ->method('foo') ->willReturn(1, 2, 3); $this->assertEquals(1, $mock->foo()); $this->assertEquals(2, $mock->foo()); $this->assertEquals(3, $mock->foo()); } public function testWillReturnOnConsecutiveCalls(): void { $mock = $this->getMockBuilder(stdClass::class) ->setMethods(['foo']) ->getMock(); $mock->expects($this->any()) ->method('foo') ->willReturnOnConsecutiveCalls(1, 2, 3); $this->assertEquals(1, $mock->foo()); $this->assertEquals(2, $mock->foo()); $this->assertEquals(3, $mock->foo()); } public function testWillReturnByReference(): void { $mock = $this->getMockBuilder(stdClass::class) ->setMethods(['foo']) ->getMock(); $mock->expects($this->any()) ->method('foo') ->willReturnReference($value); $this->assertNull($mock->foo()); $value = 'foo'; $this->assertSame('foo', $mock->foo()); $value = 'bar'; $this->assertSame('bar', $mock->foo()); } public function testWillFailWhenTryingToPerformExpectationUnconfigurableMethod(): void { $matcherCollection = new InvocationHandler([], false); $invocationMocker = new InvocationMocker( $matcherCollection, new Matcher($this->any()) ); $this->expectException(RuntimeException::class); $invocationMocker->method('someMethod'); } public function testWillReturnFailsWhenTryingToReturnSingleIncompatibleValue(): void { $mock = $this->getMockBuilder(ClassWithAllPossibleReturnTypes::class) ->getMock(); $invocationMocker = $mock->method('methodWithBoolReturnTypeDeclaration'); $this->expectException(IncompatibleReturnValueException::class); $this->expectExceptionMessage('Method methodWithBoolReturnTypeDeclaration may not return value of type integer, its return declaration is ": bool"'); $invocationMocker->willReturn(1); } public function testWillReturnFailsWhenTryingToReturnIncompatibleValueByConstraint(): void { $mock = $this->getMockBuilder(ClassWithAllPossibleReturnTypes::class) ->getMock(); $invocationMocker = $mock->method(new IsEqual('methodWithBoolReturnTypeDeclaration')); $this->expectException(IncompatibleReturnValueException::class); $this->expectExceptionMessage('Method methodWithBoolReturnTypeDeclaration may not return value of type integer, its return declaration is ": bool"'); $invocationMocker->willReturn(1); } public function testWillReturnFailsWhenTryingToReturnAtLeastOneIncompatibleValue(): void { $mock = $this->getMockBuilder(ClassWithAllPossibleReturnTypes::class) ->getMock(); $invocationMocker = $mock->method('methodWithBoolReturnTypeDeclaration'); $this->expectException(IncompatibleReturnValueException::class); $this->expectExceptionMessage('Method methodWithBoolReturnTypeDeclaration may not return value of type integer, its return declaration is ": bool"'); $invocationMocker->willReturn(true, 1); } public function testWillReturnFailsWhenTryingToReturnSingleIncompatibleClass(): void { $mock = $this->getMockBuilder(ClassWithAllPossibleReturnTypes::class) ->getMock(); $invocationMocker = $mock->method('methodWithClassReturnTypeDeclaration'); $this->expectException(IncompatibleReturnValueException::class); $this->expectExceptionMessage('Method methodWithClassReturnTypeDeclaration may not return value of type Foo, its return declaration is ": stdClass"'); $invocationMocker->willReturn(new Foo()); } public function testWillReturnAllowsMatchersForMultipleMethodsWithDifferentReturnTypes(): void { /** @var ClassWithAllPossibleReturnTypes|\PHPUnit\Framework\MockObject\MockObject $mock */ $mock = $this->getMockBuilder(ClassWithAllPossibleReturnTypes::class) ->getMock(); $invocationMocker = $mock->method(new \PHPUnit\Framework\Constraint\IsAnything()); $invocationMocker->willReturn(true, 1); $this->assertEquals(true, $mock->methodWithBoolReturnTypeDeclaration()); $this->assertEquals(1, $mock->methodWithIntReturnTypeDeclaration()); } public function testWillReturnValidType(): void { $mock = $this->getMockBuilder(ClassWithAllPossibleReturnTypes::class) ->getMock(); $mock->expects($this->any()) ->method('methodWithBoolReturnTypeDeclaration') ->willReturn(true); $this->assertEquals(true, $mock->methodWithBoolReturnTypeDeclaration()); } public function testWillReturnValidTypeForLowercaseCall(): void { $mock = $this->getMockBuilder(ClassWithAllPossibleReturnTypes::class) ->getMock(); $mock->expects($this->any()) ->method('methodWithBoolReturnTypeDeclaration') ->willReturn(true); $this->assertEquals(true, $mock->methodwithboolreturntypedeclaration()); } public function testWillReturnValidTypeForLowercaseMethod(): void { $mock = $this->getMockBuilder(ClassWithAllPossibleReturnTypes::class) ->getMock(); $mock->expects($this->any()) ->method('methodwithboolreturntypedeclaration') ->willReturn(true); $this->assertEquals(true, $mock->methodWithBoolReturnTypeDeclaration()); } /** * @see https://github.com/sebastianbergmann/phpunit/issues/3602 */ public function testWillReturnFailsWhenTryingToReturnValueFromVoidMethod(): void { /** @var ClassWithAllPossibleReturnTypes|\PHPUnit\Framework\MockObject\MockObject $out */ $out = $this->createMock(ClassWithAllPossibleReturnTypes::class); $method = $out->method('methodWithVoidReturnTypeDeclaration'); $this->expectException(IncompatibleReturnValueException::class); $this->expectExceptionMessage('Method methodWithVoidReturnTypeDeclaration may not return value of type boolean, its return declaration is ": void"'); $method->willReturn(true); } public function testExpectationsAreEnabledByPreviousMethodCallWhenChainedWithAfter(): void { $mock = $this->createMock(ClassWithImplicitProtocol::class); $mock->expects($this->once()) ->method('firstCall') ->id($fristCallId = 'first-call-id'); $mock->expects($this->once()) ->method('secondCall') ->after($fristCallId); $mock->firstCall(); $mock->secondCall(); } public function testExpectationsAreNotTriggeredUntilPreviousMethodWasCalled(): void { $mock = $this->createMock(ClassWithImplicitProtocol::class); $mock->expects($this->once()) ->method('firstCall') ->id($firstCallId = 'first-call-id'); $mock->expects($this->once()) ->method('secondCall') ->after($firstCallId); $mock->secondCall(); $mock->firstCall(); $mock->secondCall(); } public function testWillReturnAlreadyInstantiatedStubs(): void { $mock = $this->getMockBuilder(stdClass::class) ->setMethods(['foo', 'bar']) ->getMock(); $mock->expects($this->any()) ->method('foo') ->willReturn(new ReturnStub('foo')); $mock->expects($this->any()) ->method('bar') ->willReturn(new ReturnSelf()); $this->assertSame('foo', $mock->foo()); $this->assertSame($mock, $mock->bar()); } } PK!Y :Framework/MockObject/Matcher/ConsecutiveParametersTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\InvalidParameterGroupException; use PHPUnit\Framework\TestCase; /** * @small */ final class ConsecutiveParametersTest extends TestCase { public function testIntegration(): void { $mock = $this->getMockBuilder(stdClass::class) ->setMethods(['foo']) ->getMock(); $mock->expects($this->any()) ->method('foo') ->withConsecutive( ['bar'], [21, 42] ); $this->assertNull($mock->foo('bar')); $this->assertNull($mock->foo(21, 42)); } public function testIntegrationWithLessAssertionsThanMethodCalls(): void { $mock = $this->getMockBuilder(stdClass::class) ->setMethods(['foo']) ->getMock(); $mock->expects($this->any()) ->method('foo') ->withConsecutive( ['bar'] ); $this->assertNull($mock->foo('bar')); $this->assertNull($mock->foo(21, 42)); } public function testIntegrationExpectingException(): void { $mock = $this->getMockBuilder(stdClass::class) ->setMethods(['foo']) ->getMock(); $mock->expects($this->any()) ->method('foo') ->withConsecutive( ['bar'], [21, 42] ); $mock->foo('bar'); $this->expectException(ExpectationFailedException::class); $mock->foo('invalid'); } public function testIntegrationFailsWithNonIterableParameterGroup(): void { $mock = $this->getMockBuilder(stdClass::class) ->setMethods(['foo']) ->getMock(); $this->expectException(InvalidParameterGroupException::class); $this->expectExceptionMessage('Parameter group #1 must be an array or Traversable, got object'); $mock->expects($this->any()) ->method('foo') ->withConsecutive( ['bar'], $this->identicalTo([21, 42]) // this is not an array ); } } PK!?;'Framework/MockObject/MockMethodTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\TestCase; use PHPUnit\TestFixture\MockObject\ClassWithoutParentButParentReturnType; use SebastianBergmann\Type\UnknownType; /** * @small */ final class MockMethodTest extends TestCase { public function testGetNameReturnsMethodName(): void { $method = new MockMethod( 'ClassName', 'methodName', false, '', '', '', new UnknownType, '', false, false, null, false ); $this->assertEquals('methodName', $method->getName()); } /** * @requires PHP < 7.4 */ public function testFailWhenReturnTypeIsParentButThereIsNoParentClass(): void { $class = new \ReflectionClass(ClassWithoutParentButParentReturnType::class); $this->expectException(\RuntimeException::class); MockMethod::fromReflection($class->getMethod('foo'), false, false); } } PK!q((&Framework/MockObject/GeneratorTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use PHPUnit\Framework\MockObject\Generator; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** * @covers \PHPUnit\Framework\MockObject\Generator * * @uses \PHPUnit\Framework\MockObject\InvocationHandler * @uses \PHPUnit\Framework\MockObject\Builder\InvocationMocker * @uses \PHPUnit\Framework\MockObject\Invocation * @uses \PHPUnit\Framework\MockObject\Matcher * @uses \PHPUnit\Framework\MockObject\Rule\InvocationOrder * @uses \PHPUnit\Framework\MockObject\Rule\MethodName * @uses \PHPUnit\Framework\MockObject\Stub\ReturnStub * @uses \PHPUnit\Framework\MockObject\Rule\InvokedCount * * @small */ final class GeneratorTest extends TestCase { /** * @var Generator */ private $generator; protected function setUp(): void { $this->generator = new Generator; } public function testGetMockThrowsExceptionWhenInvalidFunctionNameIsPassedInAsAFunctionToMock(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $this->generator->getMock(stdClass::class, [0]); } public function testGetMockThrowsExceptionWithInvalidClassArgumentType(): void { $this->expectException(\PHPUnit\Framework\InvalidArgumentException::class); $this->generator->getMock(false); } public function testGetMockThrowsExceptionWithInvalidMethods(): void { $this->expectException(\PHPUnit\Framework\InvalidArgumentException::class); $this->generator->getMock(stdClass::class, false); } public function testGetMockThrowsExceptionWithNonExistingClass(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $this->assertFalse(\class_exists('Tux')); $this->generator->getMock('Tux', [], [], '', true, true, false, true, false, null, false); } public function testGetMockThrowsExceptionWithNonExistingClasses(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $this->assertFalse(\class_exists('Tux')); $this->generator->getMock(['Tux', false], [], [], '', true, true, false, true, false, null, false); } public function testGetMockThrowsExceptionWithExistingClassAsMockName(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $this->generator->getMock(stdClass::class, [], [], RuntimeException::class); } public function testGetMockCanCreateNonExistingFunctions(): void { $mock = $this->generator->getMock(stdClass::class, ['testFunction']); $this->assertTrue(\method_exists($mock, 'testFunction')); } public function testGetMockGeneratorThrowsException(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $this->expectExceptionMessage('duplicates: "foo, bar, foo" (duplicate: "foo")'); $this->generator->getMock(stdClass::class, ['foo', 'bar', 'foo']); } public function testGetMockBlacklistedMethodNamesPhp7(): void { $mock = $this->generator->getMock(InterfaceWithSemiReservedMethodName::class); $this->assertTrue(\method_exists($mock, 'unset')); $this->assertInstanceOf(InterfaceWithSemiReservedMethodName::class, $mock); } public function testGetMockForAbstractClassDoesNotFailWhenFakingInterfaces(): void { $mock = $this->generator->getMockForAbstractClass(Countable::class); $this->assertTrue(\method_exists($mock, 'count')); } public function testGetMockForAbstractClassStubbingAbstractClass(): void { $mock = $this->generator->getMockForAbstractClass(AbstractMockTestClass::class); $this->assertTrue(\method_exists($mock, 'doSomething')); } public function testGetMockForAbstractClassWithNonExistentMethods(): void { $mock = $this->generator->getMockForAbstractClass( AbstractMockTestClass::class, [], '', true, true, true, ['nonexistentMethod'] ); $this->assertTrue(\method_exists($mock, 'nonexistentMethod')); $this->assertTrue(\method_exists($mock, 'doSomething')); } public function testGetMockForAbstractClassShouldCreateStubsOnlyForAbstractMethodWhenNoMethodsWereInformed(): void { $mock = $this->generator->getMockForAbstractClass(AbstractMockTestClass::class); $mock->expects($this->any()) ->method('doSomething') ->willReturn('testing'); $this->assertEquals('testing', $mock->doSomething()); $this->assertEquals(1, $mock->returnAnything()); } public function testGetMockForAbstractClassAbstractClassDoesNotExist(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $this->generator->getMockForAbstractClass('Tux'); } public function testGetMockForTraitWithNonExistentMethodsAndNonAbstractMethods(): void { $mock = $this->generator->getMockForTrait( AbstractTrait::class, [], '', true, true, true, ['nonexistentMethod'] ); $this->assertTrue(\method_exists($mock, 'nonexistentMethod')); $this->assertTrue(\method_exists($mock, 'doSomething')); $this->assertTrue($mock->mockableMethod()); $this->assertTrue($mock->anotherMockableMethod()); } public function testGetMockForTraitStubbingAbstractMethod(): void { $mock = $this->generator->getMockForTrait(AbstractTrait::class); $this->assertTrue(\method_exists($mock, 'doSomething')); } public function testGetMockForTraitWithNonExistantTrait(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $mock = $this->generator->getMockForTrait('Tux'); } public function testGetObjectForTraitWithNonExistantTrait(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $mock = $this->generator->getObjectForTrait('Tux'); } public function testGetMockClassMethodsForNonExistantClass(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $mock = $this->generator->mockClassMethods('Tux', true, true); } public function testGetMockForSingletonWithReflectionSuccess(): void { $mock = $this->generator->getMock(SingletonClass::class, ['doSomething'], [], '', false); $this->assertInstanceOf('SingletonClass', $mock); } public function testExceptionIsRaisedForMutuallyExclusiveOptions(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $this->generator->getMock(stdClass::class, [], [], '', false, true, true, true, true); } public function testCanImplementInterfacesThatHaveMethodsWithReturnTypes(): void { $stub = $this->generator->getMock([AnInterfaceWithReturnType::class, AnInterface::class]); $this->assertInstanceOf(AnInterfaceWithReturnType::class, $stub); $this->assertInstanceOf(AnInterface::class, $stub); $this->assertInstanceOf(MockObject::class, $stub); } public function testCanConfigureMethodsForDoubleOfNonExistentClass(): void { $className = 'X' . \md5(\microtime()); $mock = $this->generator->getMock($className, ['someMethod']); $this->assertInstanceOf($className, $mock); } public function testCanInvokeMethodsOfNonExistentClass(): void { $className = 'X' . \md5(\microtime()); $mock = $this->generator->getMock($className, ['someMethod']); $mock->expects($this->once())->method('someMethod'); $this->assertNull($mock->someMethod()); } public function testMockingOfExceptionWithThrowable(): void { $stub = $this->generator->getMock(ExceptionWithThrowable::class); $this->assertInstanceOf(ExceptionWithThrowable::class, $stub); $this->assertInstanceOf(Exception::class, $stub); $this->assertInstanceOf(MockObject::class, $stub); } public function testMockingOfThrowable(): void { $stub = $this->generator->getMock(Throwable::class); $this->assertInstanceOf(Throwable::class, $stub); $this->assertInstanceOf(Exception::class, $stub); $this->assertInstanceOf(MockObject::class, $stub); } public function testMockingOfThrowableConstructorArguments(): void { $mock = $this->generator->getMock(Throwable::class, null, ['It works']); $this->assertSame('It works', $mock->getMessage()); } public function testVariadicArgumentsArePassedToOriginalMethod(): void { /** @var ClassWithVariadicArgumentMethod|MockObject $mock */ $mock = $this->generator->getMock( ClassWithVariadicArgumentMethod::class, [], [], '', true, false, true, false, true ); $arguments = [1, 'foo', false]; $this->assertSame($arguments, $mock->foo(...$arguments)); } public function testVariadicArgumentsArePassedToMockedMethod(): void { /** @var ClassWithVariadicArgumentMethod|MockObject $mock */ $mock = $this->createMock(ClassWithVariadicArgumentMethod::class); $arguments = [1, 'foo', false]; $mock->expects($this->once()) ->method('foo') ->with(...$arguments); $mock->foo(...$arguments); } public function testGetClassMethodsWithNonExistingClass(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $this->generator->getClassMethods('Tux'); } public function testCannotMockFinalClass(): void { $this->expectException(\PHPUnit\Framework\MockObject\RuntimeException::class); $mock = $this->createMock(FinalClass::class); } } PK!^"/Framework/MockObject/ConfigurableMethodTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\TestCase; use SebastianBergmann\Type\Type; final class ConfigurableMethodTest extends TestCase { public function testMethodMayReturnAssignableValue(): void { $assignableType = $this->createMock(Type::class); $assignableType->method('isAssignable') ->willReturn(true); $configurable = new ConfigurableMethod('foo', $assignableType); $this->assertTrue($configurable->mayReturn('everything-is-valid')); } public function testMethodMayNotReturnUnassignableValue(): void { $unassignableType = $this->createMock(Type::class); $unassignableType->method('isAssignable') ->willReturn(false); $configurable = new ConfigurableMethod('foo', $unassignableType); $this->assertFalse($configurable->mayReturn('everything-is-invalid')); } } PK!,$QQ$Framework/MockObject/MatcherTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\MockObject\Rule\InvocationOrder; use PHPUnit\Framework\MockObject\Rule\MethodName; use PHPUnit\Framework\MockObject\Rule\ParametersRule; use PHPUnit\Framework\TestCase; /** * @covers \PHPUnit\Framework\MockObject\Matcher */ class MatcherTest extends TestCase { public function testParameterRuleIsAppliedToInvocation(): void { $invocationMatcher = $this->createStub(InvocationOrder::class); $invocation = new Invocation('Foo', 'bar', [], 'void', new \stdClass); $parameterRule = $this->createMock(ParametersRule::class); $parameterRule->expects($this->once()) ->method('apply') ->with($invocation); $matcher = new Matcher($invocationMatcher); $matcher->setMethodNameRule(new MethodName('bar')); $matcher->setParametersRule($parameterRule); $matcher->invoked($invocation); } public function testParametersRuleTriggersFailOfInvocation(): void { $invocationMatcher = $this->createStub(InvocationOrder::class); $invocation = new Invocation('Foo', 'bar', [], 'void', new \stdClass); $parameterRule = $this->createStub(ParametersRule::class); $parameterRule->method('apply') ->willThrowException(new ExpectationFailedException('rule is always violated.')); $matcher = new Matcher($invocationMatcher); $matcher->setMethodNameRule(new MethodName('bar')); $matcher->setParametersRule($parameterRule); $this->expectException(ExpectationFailedException::class); $this->expectExceptionMessage("Expectation failed for method name is \"bar\" when \nrule is always violated."); $matcher->invoked($invocation); } public function testParameterRuleDoesNotInfluenceMatches(): void { $invocationMatcher = $this->createStub(InvocationOrder::class); $invocationMatcher->method('matches') ->willReturn(true); $invocation = new Invocation('Foo', 'bar', [], 'void', new \stdClass); $matcher = new Matcher($invocationMatcher); $matcher->setMethodNameRule(new MethodName('bar')); $parameterRule = $this->createStub(ParametersRule::class); $parameterRule->method('apply') ->willThrowException(new \Exception('This method should not have been called.')); $matcher->setParametersRule($parameterRule); $this->assertTrue($matcher->matches($invocation)); } public function testStubIsNotInvokedIfParametersRuleIsViolated(): void { $invocationMatcher = $this->createStub(InvocationOrder::class); $invocation = new Invocation('Foo', 'bar', [], 'void', new \stdClass); $stub = $this->createMock(Stub\Stub::class); $stub->expects($this->never()) ->method('invoke'); $parameterRule = $this->createStub(ParametersRule::class); $parameterRule->method('apply') ->willThrowException(new ExpectationFailedException('rule is always violated.')); $matcher = new Matcher($invocationMatcher); $matcher->setMethodNameRule(new MethodName('bar')); $matcher->setParametersRule($parameterRule); $matcher->setStub($stub); try { $matcher->invoked($invocation); } catch (ExpectationFailedException $e) { } } public function testStubIsInvokedIfAllMatchersAndRulesApply(): void { $invocationMatcher = $this->createStub(InvocationOrder::class); $invocation = new Invocation('Foo', 'bar', [], 'void', new \stdClass); $stub = $this->createMock(Stub\Stub::class); $stub->expects($this->once()) ->method('invoke') ->with($invocation); $parameterRule = $this->createStub(ParametersRule::class); $matcher = new Matcher($invocationMatcher); $matcher->setMethodNameRule(new MethodName('bar')); $matcher->setParametersRule($parameterRule); $matcher->setStub($stub); $matcher->invoked($invocation); } } PK!I^.Framework/MockObject/InvocationHandlerTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\TestCase; class InvocationHandlerTest extends TestCase { public function testExceptionThrownIn__ToStringIsDeferred(): void { $mock = $this->createMock(\StringableClass::class); $mock->method('__toString') ->willThrowException(new \RuntimeException('planned error')); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('planned error'); $mock->__toString(); } } PK!^q (Framework/MockObject/ProxyObjectTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** * @small */ final class ProxyObjectTest extends TestCase { public function testProxyingWorksForMethodThatReturnsUndeclaredScalarValue(): void { $proxy = $this->createTestProxy(TestProxyFixture::class); $proxy->expects($this->once()) ->method('returnString'); \assert($proxy instanceof MockObject); \assert($proxy instanceof TestProxyFixture); $this->assertSame('result', $proxy->returnString()); } public function testProxyingWorksForMethodThatReturnsDeclaredScalarValue(): void { $proxy = $this->createTestProxy(TestProxyFixture::class); $proxy->expects($this->once()) ->method('returnTypedString'); \assert($proxy instanceof MockObject); \assert($proxy instanceof TestProxyFixture); $this->assertSame('result', $proxy->returnTypedString()); } public function testProxyingWorksForMethodThatReturnsUndeclaredObject(): void { $proxy = $this->createTestProxy(TestProxyFixture::class); $proxy->expects($this->once()) ->method('returnObject'); \assert($proxy instanceof MockObject); \assert($proxy instanceof TestProxyFixture); $this->assertSame('bar', $proxy->returnObject()->foo); } public function testProxyingWorksForMethodThatReturnsDeclaredObject(): void { $proxy = $this->createTestProxy(TestProxyFixture::class); $proxy->expects($this->once()) ->method('returnTypedObject'); \assert($proxy instanceof MockObject); \assert($proxy instanceof TestProxyFixture); $this->assertSame('bar', $proxy->returnTypedObject()->foo); } public function testProxyingWorksForMethodThatReturnsUndeclaredObjectOfFinalClass(): void { $proxy = $this->createTestProxy(TestProxyFixture::class); $proxy->expects($this->once()) ->method('returnObjectOfFinalClass'); \assert($proxy instanceof MockObject); \assert($proxy instanceof TestProxyFixture); $this->assertSame('value', $proxy->returnObjectOfFinalClass()->value()); } public function testProxyingWorksForMethodThatReturnsDeclaredObjectOfFinalClass(): void { $proxy = $this->createTestProxy(TestProxyFixture::class); $proxy->expects($this->once()) ->method('returnTypedObjectOfFinalClass'); \assert($proxy instanceof MockObject); \assert($proxy instanceof TestProxyFixture); $this->assertSame('value', $proxy->returnTypedObjectOfFinalClass()->value()); } } PK!^&##(Framework/MockObject/MockBuilderTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use PHPUnit\Framework\MockObject\MockBuilder; use PHPUnit\Framework\TestCase; /** * @small */ final class MockBuilderTest extends TestCase { public function testMockBuilderRequiresClassName(): void { $mock = $this->getMockBuilder(Mockable::class)->getMock(); $this->assertInstanceOf(Mockable::class, $mock); } public function testByDefaultMocksAllMethods(): void { $mock = $this->getMockBuilder(Mockable::class)->getMock(); $this->assertNull($mock->mockableMethod()); $this->assertNull($mock->anotherMockableMethod()); } public function testMethodsToMockCanBeSpecified(): void { $mock = $this->getMockBuilder(Mockable::class) ->setMethods(['mockableMethod']) ->getMock(); $this->assertNull($mock->mockableMethod()); $this->assertTrue($mock->anotherMockableMethod()); } public function testMethodExceptionsToMockCanBeSpecified(): void { $mock = $this->getMockBuilder(Mockable::class) ->setMethodsExcept(['mockableMethod']) ->getMock(); $this->assertTrue($mock->mockableMethod()); $this->assertNull($mock->anotherMockableMethod()); } public function testSetMethodsAllowsNonExistentMethodNames(): void { $mock = $this->getMockBuilder(Mockable::class) ->setMethods(['mockableMethodWithCrazyName']) ->getMock(); $this->assertNull($mock->mockableMethodWithCrazyName()); } public function testOnlyMethodsWithNonExistentMethodNames(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Trying to set mock method "mockableMethodWithCrazyName" with onlyMethods, but it does not exist in class "Mockable". Use addMethods() for methods that don\'t exist in the class.'); $this->getMockBuilder(Mockable::class) ->onlyMethods(['mockableMethodWithCrazyName']) ->getMock(); } public function testOnlyMethodsWithExistingMethodNames(): void { $mock = $this->getMockBuilder(Mockable::class) ->onlyMethods(['mockableMethod']) ->getMock(); $this->assertNull($mock->mockableMethod()); $this->assertTrue($mock->anotherMockableMethod()); } public function testOnlyMethodsWithEmptyArray(): void { $mock = $this->getMockBuilder(Mockable::class) ->onlyMethods([]) ->getMock(); $this->assertTrue($mock->mockableMethod()); } public function testAddMethodsWithNonExistentMethodNames(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Trying to set mock method "mockableMethod" with addMethods(), but it exists in class "Mockable". Use onlyMethods() for methods that exist in the class.'); $this->getMockBuilder(Mockable::class) ->addMethods(['mockableMethod']) ->getMock(); } public function testAddMethodsWithExistingMethodNames(): void { $mock = $this->getMockBuilder(Mockable::class) ->addMethods(['mockableMethodWithFakeMethod']) ->getMock(); $this->assertNull($mock->mockableMethodWithFakeMethod()); $this->assertTrue($mock->anotherMockableMethod()); } public function testAddMethodsWithEmptyArray(): void { $mock = $this->getMockBuilder(Mockable::class) ->addMethods([]) ->getMock(); $this->assertTrue($mock->mockableMethod()); } public function testEmptyMethodExceptionsToMockCanBeSpecified(): void { $mock = $this->getMockBuilder(Mockable::class) ->setMethodsExcept() ->getMock(); $this->assertNull($mock->mockableMethod()); $this->assertNull($mock->anotherMockableMethod()); } public function testAbleToUseAddMethodsAfterOnlyMethods(): void { $mock = $this->getMockBuilder(Mockable::class) ->onlyMethods(['mockableMethod']) ->addMethods(['mockableMethodWithFakeMethod']) ->getMock(); $this->assertNull($mock->mockableMethod()); $this->assertNull($mock->mockableMethodWithFakeMethod()); } public function testAbleToUseOnlyMethodsAfterAddMethods(): void { $mock = $this->getMockBuilder(Mockable::class) ->addMethods(['mockableMethodWithFakeMethod']) ->onlyMethods(['mockableMethod']) ->getMock(); $this->assertNull($mock->mockableMethodWithFakeMethod()); $this->assertNull($mock->mockableMethod()); } public function testAbleToUseSetMethodsAfterOnlyMethods(): void { $mock = $this->getMockBuilder(Mockable::class) ->onlyMethods(['mockableMethod']) ->setMethods(['mockableMethodWithCrazyName']) ->getMock(); $this->assertNull($mock->mockableMethodWithCrazyName()); } public function testAbleToUseSetMethodsAfterAddMethods(): void { $mock = $this->getMockBuilder(Mockable::class) ->addMethods(['notAMethod']) ->setMethods(['mockableMethodWithCrazyName']) ->getMock(); $this->assertNull($mock->mockableMethodWithCrazyName()); } public function testAbleToUseAddMethodsAfterSetMethods(): void { $mock = $this->getMockBuilder(Mockable::class) ->setMethods(['mockableMethod']) ->addMethods(['mockableMethodWithFakeMethod']) ->getMock(); $this->assertNull($mock->mockableMethod()); $this->assertNull($mock->mockableMethodWithFakeMethod()); } public function testAbleToUseOnlyMethodsAfterSetMethods(): void { $mock = $this->getMockBuilder(Mockable::class) ->setMethods(['mockableMethodWithFakeMethod']) ->onlyMethods(['mockableMethod']) ->getMock(); $this->assertNull($mock->mockableMethod()); $this->assertNull($mock->mockableMethodWithFakeMethod()); } public function testAbleToUseAddMethodsAfterSetMethodsWithNull(): void { $mock = $this->getMockBuilder(Mockable::class) ->setMethods() ->addMethods(['mockableMethodWithFakeMethod']) ->getMock(); $this->assertNull($mock->mockableMethodWithFakeMethod()); } public function testByDefaultDoesNotPassArgumentsToTheConstructor(): void { $mock = $this->getMockBuilder(Mockable::class)->getMock(); $this->assertEquals([null, null], $mock->constructorArgs); } public function testMockClassNameCanBeSpecified(): void { $mock = $this->getMockBuilder(Mockable::class) ->setMockClassName('ACustomClassName') ->getMock(); $this->assertInstanceOf(ACustomClassName::class, $mock); } public function testConstructorArgumentsCanBeSpecified(): void { $mock = $this->getMockBuilder(Mockable::class) ->setConstructorArgs([23, 42]) ->getMock(); $this->assertEquals([23, 42], $mock->constructorArgs); } public function testOriginalConstructorCanBeDisabled(): void { $mock = $this->getMockBuilder(Mockable::class) ->disableOriginalConstructor() ->getMock(); $this->assertNull($mock->constructorArgs); } public function testByDefaultOriginalCloneIsPreserved(): void { $mock = $this->getMockBuilder(Mockable::class) ->getMock(); $cloned = clone $mock; $this->assertTrue($cloned->cloned); } public function testOriginalCloneCanBeDisabled(): void { $mock = $this->getMockBuilder(Mockable::class) ->disableOriginalClone() ->getMock(); $mock->cloned = false; $cloned = clone $mock; $this->assertFalse($cloned->cloned); } public function testProvidesAFluentInterface(): void { $spec = $this->getMockBuilder(Mockable::class) ->setMethods(['mockableMethod']) ->setConstructorArgs([]) ->setMockClassName('DummyClassName') ->disableOriginalConstructor() ->disableOriginalClone() ->disableAutoload(); $this->assertInstanceOf(MockBuilder::class, $spec); } } PK!hŃMM0Framework/MockObject/ConfigurableMethodsTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\TestCase; use PHPUnit\TestFixture\MockObject\AnotherClassUsingConfigurableMethods; use PHPUnit\TestFixture\MockObject\ClassUsingConfigurableMethods; use PHPUnit\TestFixture\MockObject\ReinitializeConfigurableMethods; use SebastianBergmann\Type\SimpleType; final class ConfigurableMethodsTest extends TestCase { public function testTwoClassesUsingConfigurableMethodsDontInterfere(): void { $configurableMethodsA = [new ConfigurableMethod('foo', SimpleType::fromValue('boolean', false))]; $configurableMethodsB = []; ClassUsingConfigurableMethods::__phpunit_initConfigurableMethods(...$configurableMethodsA); AnotherClassUsingConfigurableMethods::__phpunit_initConfigurableMethods(...$configurableMethodsB); $this->assertSame($configurableMethodsA, ClassUsingConfigurableMethods::getConfigurableMethods()); $this->assertSame($configurableMethodsB, AnotherClassUsingConfigurableMethods::getConfigurableMethods()); } public function testConfigurableMethodsAreImmutable(): void { ReinitializeConfigurableMethods::__phpunit_initConfigurableMethods(); $this->expectException(ConfigurableMethodsAlreadyInitializedException::class); ReinitializeConfigurableMethods::__phpunit_initConfigurableMethods(); } } PK!ӐFramework/TestListenerTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use MyTestListener; /** * @small */ final class TestListenerTest extends TestCase { /** * @var TestResult */ private $result; /** * @var MyTestListener */ private $listener; protected function setUp(): void { $this->result = new TestResult; $this->listener = new MyTestListener; $this->result->addListener($this->listener); } public function testError(): void { $test = new \TestError; $test->run($this->result); $this->assertEquals(1, $this->listener->errorCount()); $this->assertEquals(1, $this->listener->endCount()); } public function testFailure(): void { $test = new \Failure; $test->run($this->result); $this->assertEquals(1, $this->listener->failureCount()); $this->assertEquals(1, $this->listener->endCount()); } public function testStartStop(): void { $test = new \Success; $test->run($this->result); $this->assertEquals(1, $this->listener->startCount()); $this->assertEquals(1, $this->listener->endCount()); } } PK!:ГZ#Framework/TestSuiteIteratorTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; /** * @small */ final class TestSuiteIteratorTest extends TestCase { public function testKeyForEmptyTestSuiteInitiallyReturnsZero(): void { $testSuite = new TestSuite; $subject = new TestSuiteIterator($testSuite); $this->assertSame(0, $subject->key()); } public function testValidForEmptyTestSuiteInitiallyReturnsFalse(): void { $testSuite = new TestSuite; $subject = new TestSuiteIterator($testSuite); $this->assertFalse($subject->valid()); } public function testKeyForNonEmptyTestSuiteInitiallyReturnsZero(): void { $subject = new TestSuiteIterator($this->suiteWithEmptyTestCase()); $this->assertSame(0, $subject->key()); } public function testValidForNonEmptyTestSuiteInitiallyReturnsTrue(): void { $subject = new TestSuiteIterator($this->suiteWithEmptyTestCase()); $this->assertTrue($subject->valid()); } public function testCurrentForNonEmptyTestSuiteInitiallyReturnsFirstTest(): void { $test = new \EmptyTestCaseTest; $testSuite = new TestSuite; $testSuite->addTest($test); $subject = new TestSuiteIterator($testSuite); $this->assertSame($test, $subject->current()); } public function testRewindResetsKeyToZero(): void { $subject = new TestSuiteIterator($this->suiteWithEmptyTestCase()); $subject->next(); $subject->rewind(); $this->assertSame(0, $subject->key()); } public function testRewindResetsCurrentToFirstElement(): void { $testSuite = new TestSuite; $test = new \EmptyTestCaseTest; $testSuite->addTest($test); $subject = new TestSuiteIterator($testSuite); $subject->next(); $subject->rewind(); $this->assertSame($test, $subject->current()); } public function testNextIncreasesKeyFromZeroToOne(): void { $subject = new TestSuiteIterator($this->suiteWithEmptyTestCase()); $subject->next(); $this->assertSame(1, $subject->key()); } public function testValidAfterLastElementReturnsFalse(): void { $subject = new TestSuiteIterator($this->suiteWithEmptyTestCase()); $subject->next(); $this->assertFalse($subject->valid()); } public function testGetChildrenForEmptyTestSuiteThrowsException(): void { $subject = new TestSuiteIterator(new TestSuite); $this->expectException(NoChildTestSuiteException::class); $subject->getChildren(); } public function testGetChildrenForCurrentTestThrowsException(): void { $subject = new TestSuiteIterator($this->suiteWithEmptyTestCase()); $this->expectException(NoChildTestSuiteException::class); $subject->getChildren(); } public function testGetChildrenReturnsNewInstanceWithCurrentTestSuite(): void { $childSuite = new TestSuite; $test = new \EmptyTestCaseTest; $childSuite->addTest($test); $testSuite = new TestSuite; $testSuite->addTest($childSuite); $subject = new TestSuiteIterator($testSuite); $children = $subject->getChildren(); $this->assertNotSame($subject, $children); $this->assertSame($test, $children->current()); } public function testHasChildrenForCurrentTestSuiteReturnsTrue(): void { $testSuite = new TestSuite; $childSuite = new TestSuite; $testSuite->addTest($childSuite); $subject = new TestSuiteIterator($testSuite); $this->assertTrue($subject->hasChildren()); } public function testHasChildrenForCurrentTestReturnsFalse(): void { $subject = new TestSuiteIterator($this->suiteWithEmptyTestCase()); $this->assertFalse($subject->hasChildren()); } public function testHasChildrenForNoTestsReturnsFalse(): void { $subject = new TestSuiteIterator(new TestSuite); $this->assertFalse($subject->hasChildren()); } private function suiteWithEmptyTestCase(): TestSuite { $suite = new TestSuite; $suite->addTest(new \EmptyTestCaseTest); return $suite; } } PK!GG?yyFramework/ConstraintTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use PHPUnit\Framework\Constraint\Count; use PHPUnit\Framework\Constraint\SameSize; use PHPUnit\Framework\Constraint\TraversableContains; use PHPUnit\Util\Filter; /** * @small */ final class ConstraintTest extends TestCase { public function testConstraintArrayNotHasKey(): void { $constraint = Assert::logicalNot( Assert::arrayHasKey(0) ); $this->assertFalse($constraint->evaluate([0 => 1], '', true)); $this->assertEquals('does not have the key 0', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate([0 => 1]); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintArrayNotHasKey2(): void { $constraint = Assert::logicalNot( Assert::arrayHasKey(0) ); try { $constraint->evaluate([0], 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintFileNotExists(): void { $file = TEST_FILES_PATH . 'ClassWithNonPublicAttributes.php'; $constraint = Assert::logicalNot( Assert::fileExists() ); $this->assertFalse($constraint->evaluate($file, '', true)); $this->assertEquals('file does not exist', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate($file); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintFileNotExists2(): void { $file = TEST_FILES_PATH . 'ClassWithNonPublicAttributes.php'; $constraint = Assert::logicalNot( Assert::fileExists() ); try { $constraint->evaluate($file, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintNotGreaterThan(): void { $constraint = Assert::logicalNot( Assert::greaterThan(1) ); $this->assertTrue($constraint->evaluate(1, '', true)); $this->assertEquals('is not greater than 1', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(2); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintNotGreaterThan2(): void { $constraint = Assert::logicalNot( Assert::greaterThan(1) ); try { $constraint->evaluate(2, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintGreaterThanOrEqual(): void { $constraint = Assert::greaterThanOrEqual(1); $this->assertTrue($constraint->evaluate(1, '', true)); $this->assertFalse($constraint->evaluate(0, '', true)); $this->assertEquals('is equal to 1 or is greater than 1', $constraint->toString()); $this->assertCount(2, $constraint); try { $constraint->evaluate(0); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintGreaterThanOrEqual2(): void { $constraint = Assert::greaterThanOrEqual(1); try { $constraint->evaluate(0, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintNotGreaterThanOrEqual(): void { $constraint = Assert::logicalNot( Assert::greaterThanOrEqual(1) ); $this->assertFalse($constraint->evaluate(1, '', true)); $this->assertEquals('not( is equal to 1 or is greater than 1 )', $constraint->toString()); $this->assertCount(2, $constraint); try { $constraint->evaluate(1); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintNotGreaterThanOrEqual2(): void { $constraint = Assert::logicalNot( Assert::greaterThanOrEqual(1) ); try { $constraint->evaluate(1, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsAnything(): void { $constraint = Assert::anything(); $this->assertTrue($constraint->evaluate(null, '', true)); $this->assertNull($constraint->evaluate(null)); $this->assertEquals('is anything', $constraint->toString()); $this->assertCount(0, $constraint); } public function testConstraintNotIsAnything(): void { $constraint = Assert::logicalNot( Assert::anything() ); $this->assertFalse($constraint->evaluate(null, '', true)); $this->assertEquals('is not anything', $constraint->toString()); $this->assertCount(0, $constraint); try { $constraint->evaluate(null); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsNotEqual(): void { $constraint = Assert::logicalNot( Assert::equalTo(1) ); $this->assertTrue($constraint->evaluate(0, '', true)); $this->assertFalse($constraint->evaluate(1, '', true)); $this->assertEquals('is not equal to 1', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(1); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsNotEqual2(): void { $constraint = Assert::logicalNot( Assert::equalTo(1) ); try { $constraint->evaluate(1, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsNotIdentical(): void { $a = new \stdClass; $b = new \stdClass; $constraint = Assert::logicalNot( Assert::identicalTo($a) ); $this->assertTrue($constraint->evaluate($b, '', true)); $this->assertFalse($constraint->evaluate($a, '', true)); $this->assertEquals('is not identical to an object of class "stdClass"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate($a); } catch (ExpectationFailedException $e) { $this->assertEquals( <<trimnl(TestFailure::exceptionToString($e)) ); return; } $this->fail(); } public function testConstraintIsNotIdentical2(): void { $a = new \stdClass; $constraint = Assert::logicalNot( Assert::identicalTo($a) ); try { $constraint->evaluate($a, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsNotIdentical3(): void { $constraint = Assert::logicalNot( Assert::identicalTo('a') ); try { $constraint->evaluate('a', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<trimnl(TestFailure::exceptionToString($e)) ); return; } $this->fail(); } public function testConstraintIsInstanceOf(): void { $constraint = Assert::isInstanceOf(\Exception::class); $this->assertFalse($constraint->evaluate(new \stdClass, '', true)); $this->assertTrue($constraint->evaluate(new \Exception, '', true)); $this->assertEquals('is instance of class "Exception"', $constraint->toString()); $this->assertCount(1, $constraint); $interfaceConstraint = Assert::isInstanceOf(\Countable::class); $this->assertFalse($interfaceConstraint->evaluate(new \stdClass, '', true)); $this->assertTrue($interfaceConstraint->evaluate(new \ArrayObject, '', true)); $this->assertEquals('is instance of interface "Countable"', $interfaceConstraint->toString()); try { $constraint->evaluate(new \stdClass); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsInstanceOf2(): void { $constraint = Assert::isInstanceOf(\Exception::class); try { $constraint->evaluate(new \stdClass, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsNotInstanceOf(): void { $constraint = Assert::logicalNot( Assert::isInstanceOf(\stdClass::class) ); $this->assertFalse($constraint->evaluate(new \stdClass, '', true)); $this->assertTrue($constraint->evaluate(new Exception, '', true)); $this->assertEquals('is not instance of class "stdClass"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(new \stdClass); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsNotInstanceOf2(): void { $constraint = Assert::logicalNot( Assert::isInstanceOf(\stdClass::class) ); try { $constraint->evaluate(new \stdClass, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsNotType(): void { $constraint = Assert::logicalNot( Assert::isType('string') ); $this->assertTrue($constraint->evaluate(0, '', true)); $this->assertFalse($constraint->evaluate('', '', true)); $this->assertEquals('is not of type "string"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(''); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsNotType2(): void { $constraint = Assert::logicalNot( Assert::isType('string') ); try { $constraint->evaluate('', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsNotNull(): void { $constraint = Assert::logicalNot( Assert::isNull() ); $this->assertFalse($constraint->evaluate(null, '', true)); $this->assertTrue($constraint->evaluate(0, '', true)); $this->assertEquals('is not null', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(null); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintIsNotNull2(): void { $constraint = Assert::logicalNot( Assert::isNull() ); try { $constraint->evaluate(null, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintNotLessThan(): void { $constraint = Assert::logicalNot( Assert::lessThan(1) ); $this->assertTrue($constraint->evaluate(1, '', true)); $this->assertFalse($constraint->evaluate(0, '', true)); $this->assertEquals('is not less than 1', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(0); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintNotLessThan2(): void { $constraint = Assert::logicalNot( Assert::lessThan(1) ); try { $constraint->evaluate(0, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintLessThanOrEqual(): void { $constraint = Assert::lessThanOrEqual(1); $this->assertTrue($constraint->evaluate(1, '', true)); $this->assertFalse($constraint->evaluate(2, '', true)); $this->assertEquals('is equal to 1 or is less than 1', $constraint->toString()); $this->assertCount(2, $constraint); try { $constraint->evaluate(2); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintLessThanOrEqual2(): void { $constraint = Assert::lessThanOrEqual(1); try { $constraint->evaluate(2, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintNotLessThanOrEqual(): void { $constraint = Assert::logicalNot( Assert::lessThanOrEqual(1) ); $this->assertTrue($constraint->evaluate(2, '', true)); $this->assertFalse($constraint->evaluate(1, '', true)); $this->assertEquals('not( is equal to 1 or is less than 1 )', $constraint->toString()); $this->assertCount(2, $constraint); try { $constraint->evaluate(1); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintNotLessThanOrEqual2(): void { $constraint = Assert::logicalNot( Assert::lessThanOrEqual(1) ); try { $constraint->evaluate(1, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintClassNotHasAttribute(): void { $constraint = Assert::logicalNot( Assert::classHasAttribute('privateAttribute') ); $this->assertTrue($constraint->evaluate(\stdClass::class, '', true)); $this->assertFalse($constraint->evaluate(\ClassWithNonPublicAttributes::class, '', true)); $this->assertEquals('does not have attribute "privateAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(\ClassWithNonPublicAttributes::class); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintClassNotHasAttribute2(): void { $constraint = Assert::logicalNot( Assert::classHasAttribute('privateAttribute') ); try { $constraint->evaluate(\ClassWithNonPublicAttributes::class, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintClassNotHasStaticAttribute(): void { $constraint = Assert::logicalNot( Assert::classHasStaticAttribute('privateStaticAttribute') ); $this->assertTrue($constraint->evaluate(\stdClass::class, '', true)); $this->assertFalse($constraint->evaluate(\ClassWithNonPublicAttributes::class, '', true)); $this->assertEquals('does not have static attribute "privateStaticAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(\ClassWithNonPublicAttributes::class); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintClassNotHasStaticAttribute2(): void { $constraint = Assert::logicalNot( Assert::classHasStaticAttribute('privateStaticAttribute') ); try { $constraint->evaluate(\ClassWithNonPublicAttributes::class, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintObjectNotHasAttribute(): void { $constraint = Assert::logicalNot( Assert::objectHasAttribute('privateAttribute') ); $this->assertTrue($constraint->evaluate(new \stdClass, '', true)); $this->assertFalse($constraint->evaluate(new \ClassWithNonPublicAttributes, '', true)); $this->assertEquals('does not have attribute "privateAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(new \ClassWithNonPublicAttributes); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintObjectNotHasAttribute2(): void { $constraint = Assert::logicalNot( Assert::objectHasAttribute('privateAttribute') ); try { $constraint->evaluate(new \ClassWithNonPublicAttributes, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } /** * @testdox Constraint PCRE not match */ public function testConstraintPCRENotMatch(): void { $constraint = Assert::logicalNot( Assert::matchesRegularExpression('/foo/') ); $this->assertTrue($constraint->evaluate('barbazbar', '', true)); $this->assertFalse($constraint->evaluate('barfoobar', '', true)); $this->assertEquals('does not match PCRE pattern "/foo/"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate('barfoobar'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } /** * @testdox Constraint PCRE not match with custom message */ public function testConstraintPCRENotMatch2(): void { $constraint = Assert::logicalNot( Assert::matchesRegularExpression('/foo/') ); try { $constraint->evaluate('barfoobar', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintStringStartsNotWith(): void { $constraint = Assert::logicalNot( Assert::stringStartsWith('prefix') ); $this->assertTrue($constraint->evaluate('foo', '', true)); $this->assertFalse($constraint->evaluate('prefixfoo', '', true)); $this->assertEquals('starts not with "prefix"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate('prefixfoo'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintStringStartsNotWith2(): void { $constraint = Assert::logicalNot( Assert::stringStartsWith('prefix') ); try { $constraint->evaluate('prefixfoo', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintStringNotContains(): void { $constraint = Assert::logicalNot( Assert::stringContains('foo') ); $this->assertTrue($constraint->evaluate('barbazbar', '', true)); $this->assertFalse($constraint->evaluate('barfoobar', '', true)); $this->assertEquals('does not contain "foo"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate('barfoobar'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintStringNotContainsWhenIgnoreCase(): void { $constraint = Assert::logicalNot( Assert::stringContains('oryginał') ); $this->assertTrue($constraint->evaluate('original', '', true)); $this->assertFalse($constraint->evaluate('ORYGINAŁ', '', true)); $this->assertFalse($constraint->evaluate('oryginał', '', true)); $this->assertEquals('does not contain "oryginał"', $constraint->toString()); $this->assertCount(1, $constraint); $this->expectException(ExpectationFailedException::class); $constraint->evaluate('ORYGINAŁ'); } public function testConstraintStringNotContainsForUtf8StringWhenNotIgnoreCase(): void { $constraint = Assert::logicalNot( Assert::stringContains('oryginał', false) ); $this->assertTrue($constraint->evaluate('original', '', true)); $this->assertTrue($constraint->evaluate('ORYGINAŁ', '', true)); $this->assertFalse($constraint->evaluate('oryginał', '', true)); $this->assertEquals('does not contain "oryginał"', $constraint->toString()); $this->assertCount(1, $constraint); $this->expectException(ExpectationFailedException::class); $constraint->evaluate('oryginał'); } public function testConstraintStringNotContains2(): void { $constraint = Assert::logicalNot( Assert::stringContains('foo') ); try { $constraint->evaluate('barfoobar', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintStringEndsNotWith(): void { $constraint = Assert::logicalNot( Assert::stringEndsWith('suffix') ); $this->assertTrue($constraint->evaluate('foo', '', true)); $this->assertFalse($constraint->evaluate('foosuffix', '', true)); $this->assertEquals('ends not with "suffix"', $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate('foosuffix'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintStringEndsNotWith2(): void { $constraint = Assert::logicalNot( Assert::stringEndsWith('suffix') ); try { $constraint->evaluate('foosuffix', 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintArrayNotContains(): void { $constraint = Assert::logicalNot( new TraversableContains('foo') ); $this->assertTrue($constraint->evaluate(['bar'], '', true)); $this->assertFalse($constraint->evaluate(['foo'], '', true)); $this->assertEquals("does not contain 'foo'", $constraint->toString()); $this->assertCount(1, $constraint); try { $constraint->evaluate(['foo']); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintArrayNotContains2(): void { $constraint = Assert::logicalNot( new TraversableContains('foo') ); try { $constraint->evaluate(['foo'], 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintCountWithAnArray(): void { $constraint = new Count(5); $this->assertTrue($constraint->evaluate([1, 2, 3, 4, 5], '', true)); $this->assertFalse($constraint->evaluate([1, 2, 3, 4], '', true)); } public function testConstraintCountWithAnIteratorWhichDoesNotImplementCountable(): void { $constraint = new Count(5); $this->assertTrue($constraint->evaluate(new \TestIterator([1, 2, 3, 4, 5]), '', true)); $this->assertFalse($constraint->evaluate(new \TestIterator([1, 2, 3, 4]), '', true)); } public function testConstraintCountWithAnObjectImplementingCountable(): void { $constraint = new Count(5); $this->assertTrue($constraint->evaluate(new \ArrayObject([1, 2, 3, 4, 5]), '', true)); $this->assertFalse($constraint->evaluate(new \ArrayObject([1, 2, 3, 4]), '', true)); } public function testConstraintCountFailing(): void { $constraint = new Count(5); try { $constraint->evaluate([1, 2]); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintNotCountFailing(): void { $constraint = Assert::logicalNot( new Count(2) ); try { $constraint->evaluate([1, 2]); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintNotSameSizeFailing(): void { $constraint = Assert::logicalNot( new SameSize([1, 2]) ); try { $constraint->evaluate([3, 4]); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } public function testConstraintException(): void { $constraint = new Constraint\Exception('FoobarException'); $exception = new \DummyException('Test'); $stackTrace = Filter::getFilteredStacktrace($exception); try { $constraint->evaluate($exception); } catch (ExpectationFailedException $e) { $this->assertEquals( <<fail(); } /** * Removes spaces in front of newlines * * @param string $string * * @return string */ private function trimnl($string) { return \preg_replace('/[ ]*\n/', "\n", $string); } } PK!.tFramework/TestSuiteTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; /** * @small */ final class TestSuiteTest extends TestCase { /** * @var TestResult */ private $result; protected function setUp(): void { $this->result = new TestResult; } protected function tearDown(): void { $this->result = null; } /** * @testdox TestSuite can be created with name of existing non-TestCase class */ public function testSuiteNameCanBeSameAsExistingNonTestClassName(): void { $suite = new TestSuite('stdClass'); $suite->addTestSuite(\OneTestCase::class); $suite->run($this->result); $this->assertCount(1, $this->result); } public function testAddTestSuite(): void { $suite = new TestSuite(\OneTestCase::class); $suite->run($this->result); $this->assertCount(1, $this->result); } public function testInheritedTests(): void { $suite = new TestSuite(\InheritedTestCase::class); $suite->run($this->result); $this->assertTrue($this->result->wasSuccessful()); $this->assertCount(2, $this->result); } public function testNoTestCases(): void { $suite = new TestSuite(\NoTestCases::class); $suite->run($this->result); $this->assertNotTrue($this->result->wasSuccessful()); $this->assertEquals(0, $this->result->failureCount()); $this->assertEquals(1, $this->result->warningCount()); $this->assertCount(1, $this->result); } public function testNotPublicTestCase(): void { $suite = new TestSuite(\NotPublicTestCase::class); $this->assertCount(2, $suite); } public function testNotVoidTestCase(): void { $suite = new TestSuite(\NotVoidTestCase::class); $this->assertCount(1, $suite); } public function testOneTestCase(): void { $suite = new TestSuite(\OneTestCase::class); $suite->run($this->result); $this->assertEquals(0, $this->result->errorCount()); $this->assertEquals(0, $this->result->failureCount()); $this->assertCount(1, $this->result); $this->assertTrue($this->result->wasSuccessful()); } public function testShadowedTests(): void { $suite = new TestSuite(\OverrideTestCase::class); $suite->run($this->result); $this->assertCount(1, $this->result); } public function testBeforeClassAndAfterClassAnnotations(): void { $suite = new TestSuite(\BeforeClassAndAfterClassTest::class); \BeforeClassAndAfterClassTest::resetProperties(); $suite->run($this->result); $this->assertEquals(1, \BeforeClassAndAfterClassTest::$beforeClassWasRun, '@beforeClass method was not run once for the whole suite.'); $this->assertEquals(1, \BeforeClassAndAfterClassTest::$afterClassWasRun, '@afterClass method was not run once for the whole suite.'); } public function testBeforeClassWithDataProviders(): void { $suite = new TestSuite(\BeforeClassWithOnlyDataProviderTest::class); \BeforeClassWithOnlyDataProviderTest::resetProperties(); $suite->run($this->result); $this->assertTrue(\BeforeClassWithOnlyDataProviderTest::$setUpBeforeClassWasCalled, 'setUpBeforeClass method was not run.'); $this->assertTrue(\BeforeClassWithOnlyDataProviderTest::$beforeClassWasCalled, '@beforeClass method was not run.'); } public function testBeforeAnnotation(): void { $test = new TestSuite(\BeforeAndAfterTest::class); \BeforeAndAfterTest::resetProperties(); $test->run(); $this->assertEquals(2, \BeforeAndAfterTest::$beforeWasRun); $this->assertEquals(2, \BeforeAndAfterTest::$afterWasRun); } public function testTestWithAnnotation(): void { $test = new TestSuite(\TestWithTest::class); \BeforeAndAfterTest::resetProperties(); $result = $test->run(); $this->assertCount(4, $result->passed()); } public function testSkippedTestDataProvider(): void { $suite = new TestSuite(\DataProviderSkippedTest::class); $suite->run($this->result); $this->assertEquals(3, $this->result->count()); $this->assertEquals(1, $this->result->skippedCount()); } public function testItErrorsOnlyOnceOnHookException(): void { $suite = new TestSuite(\TestCaseWithExceptionInHook::class); $suite->run($this->result); $this->assertEquals(2, $this->result->count()); $this->assertEquals(1, $this->result->errorCount()); $this->assertEquals(1, $this->result->skippedCount()); } public function testTestDataProviderDependency(): void { $suite = new TestSuite(\DataProviderDependencyTest::class); $suite->run($this->result); $skipped = $this->result->skipped(); $lastSkippedResult = \array_pop($skipped); $message = $lastSkippedResult->thrownException()->getMessage(); $this->assertStringContainsString('Test for DataProviderDependencyTest::testDependency skipped by data provider', $message); } public function testIncompleteTestDataProvider(): void { $suite = new TestSuite(\DataProviderIncompleteTest::class); $suite->run($this->result); $this->assertEquals(3, $this->result->count()); $this->assertEquals(1, $this->result->notImplementedCount()); } public function testRequirementsBeforeClassHook(): void { $suite = new TestSuite(\RequirementsClassBeforeClassHookTest::class); $suite->run($this->result); $this->assertEquals(0, $this->result->errorCount()); $this->assertEquals(1, $this->result->skippedCount()); } public function testDoNotSkipInheritedClass(): void { $suite = new TestSuite( 'DontSkipInheritedClass' ); $dir = TEST_FILES_PATH . \DIRECTORY_SEPARATOR . 'Inheritance' . \DIRECTORY_SEPARATOR; $suite->addTestFile($dir . 'InheritanceA.php'); $suite->addTestFile($dir . 'InheritanceB.php'); $result = $suite->run(); $this->assertCount(2, $result); } /** * @testdox Handles exceptions in tearDownAfterClass() */ public function testTearDownAfterClassInTestSuite(): void { $suite = new TestSuite(\ExceptionInTearDownAfterClassTest::class); $suite->run($this->result); $this->assertSame(3, $this->result->count()); $this->assertCount(1, $this->result->failures()); $failure = $this->result->failures()[0]; $this->assertSame( 'Exception in ExceptionInTearDownAfterClassTest::tearDownAfterClass' . \PHP_EOL . 'throw Exception in tearDownAfterClass()', $failure->thrownException()->getMessage() ); } } PK!?xMwwFramework/AssertTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use PHPUnit\Util\Xml; /** * @small */ final class AssertTest extends TestCase { public static function validInvalidJsonDataprovider(): array { return [ 'error syntax in expected JSON' => ['{"Mascott"::}', '{"Mascott" : "Tux"}'], 'error UTF-8 in actual JSON' => ['{"Mascott" : "Tux"}', '{"Mascott" : :}'], ]; } public function testFail(): void { try { $this->fail(); } catch (AssertionFailedError $e) { return; } throw new AssertionFailedError('Fail did not throw fail exception'); } public function testAssertContainsOnlyInstancesOf(): void { $test = [new \Book, new \Book]; $this->assertContainsOnlyInstancesOf(\Book::class, $test); $this->assertContainsOnlyInstancesOf(\stdClass::class, [new \stdClass]); $test2 = [new \Author('Test')]; $this->expectException(AssertionFailedError::class); $this->assertContainsOnlyInstancesOf(\Book::class, $test2); } public function testAssertArrayHasKeyThrowsExceptionForInvalidFirstArgument(): void { $this->expectException(Exception::class); $this->assertArrayHasKey(null, []); } public function testAssertArrayHasKeyThrowsExceptionForInvalidSecondArgument(): void { $this->expectException(Exception::class); $this->assertArrayHasKey(0, null); } public function testAssertArrayHasIntegerKey(): void { $this->assertArrayHasKey(0, ['foo']); $this->expectException(AssertionFailedError::class); $this->assertArrayHasKey(1, ['foo']); } public function testAssertArrayNotHasKeyThrowsExceptionForInvalidFirstArgument(): void { $this->expectException(Exception::class); $this->assertArrayNotHasKey(null, []); } public function testAssertArrayNotHasKeyThrowsExceptionForInvalidSecondArgument(): void { $this->expectException(Exception::class); $this->assertArrayNotHasKey(0, null); } public function testAssertArrayNotHasIntegerKey(): void { $this->assertArrayNotHasKey(1, ['foo']); $this->expectException(AssertionFailedError::class); $this->assertArrayNotHasKey(0, ['foo']); } public function testAssertArrayHasStringKey(): void { $this->assertArrayHasKey('foo', ['foo' => 'bar']); $this->expectException(AssertionFailedError::class); $this->assertArrayHasKey('bar', ['foo' => 'bar']); } public function testAssertArrayNotHasStringKey(): void { $this->assertArrayNotHasKey('bar', ['foo' => 'bar']); $this->expectException(AssertionFailedError::class); $this->assertArrayNotHasKey('foo', ['foo' => 'bar']); } public function testAssertArrayHasKeyAcceptsArrayObjectValue(): void { $array = new \ArrayObject; $array['foo'] = 'bar'; $this->assertArrayHasKey('foo', $array); } public function testAssertArrayHasKeyProperlyFailsWithArrayObjectValue(): void { $array = new \ArrayObject; $array['bar'] = 'bar'; $this->expectException(AssertionFailedError::class); $this->assertArrayHasKey('foo', $array); } public function testAssertArrayHasKeyAcceptsArrayAccessValue(): void { $array = new \SampleArrayAccess; $array['foo'] = 'bar'; $this->assertArrayHasKey('foo', $array); } public function testAssertArrayHasKeyProperlyFailsWithArrayAccessValue(): void { $array = new \SampleArrayAccess; $array['bar'] = 'bar'; $this->expectException(AssertionFailedError::class); $this->assertArrayHasKey('foo', $array); } public function testAssertArrayNotHasKeyAcceptsArrayAccessValue(): void { $array = new \ArrayObject; $array['foo'] = 'bar'; $this->assertArrayNotHasKey('bar', $array); } public function testAssertArrayNotHasKeyPropertlyFailsWithArrayAccessValue(): void { $array = new \ArrayObject; $array['bar'] = 'bar'; $this->expectException(AssertionFailedError::class); $this->assertArrayNotHasKey('bar', $array); } public function testAssertArrayContainsOnlyIntegers(): void { $this->assertContainsOnly('integer', [1, 2, 3]); $this->expectException(AssertionFailedError::class); $this->assertContainsOnly('integer', ['1', 2, 3]); } public function testAssertArrayNotContainsOnlyIntegers(): void { $this->assertNotContainsOnly('integer', ['1', 2, 3]); $this->expectException(AssertionFailedError::class); $this->assertNotContainsOnly('integer', [1, 2, 3]); } public function testAssertArrayContainsOnlyStdClass(): void { $this->assertContainsOnly('StdClass', [new \stdClass]); $this->expectException(AssertionFailedError::class); $this->assertContainsOnly('StdClass', ['StdClass']); } public function testAssertArrayNotContainsOnlyStdClass(): void { $this->assertNotContainsOnly('StdClass', ['StdClass']); $this->expectException(AssertionFailedError::class); $this->assertNotContainsOnly('StdClass', [new \stdClass]); } public function equalProvider(): array { // same |= equal return \array_merge($this->equalValues(), $this->sameValues()); } public function notEqualProvider() { return $this->notEqualValues(); } public function sameProvider(): array { return $this->sameValues(); } public function notSameProvider(): array { // not equal |= not same // equal, ¬same |= not same return \array_merge($this->notEqualValues(), $this->equalValues()); } /** * @dataProvider equalProvider * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testAssertEqualsSucceeds($a, $b): void { $this->assertEquals($a, $b); } /** * @dataProvider notEqualProvider * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testAssertEqualsFails($a, $b): void { $this->expectException(AssertionFailedError::class); $this->assertEquals($a, $b); } /** * @dataProvider notEqualProvider * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testAssertNotEqualsSucceeds($a, $b): void { $this->assertNotEquals($a, $b); } /** * @testdox assertNotEquals($a, $b) with delta $delta, canoicalize $canonicalize, ignoreCase $ignoreCase * @dataProvider equalProvider * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testAssertNotEqualsFails($a, $b): void { $this->expectException(AssertionFailedError::class); $this->assertNotEquals($a, $b); } /** * @testdox assertNotSame($a, $b) fails * @dataProvider sameProvider * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testAssertSameSucceeds($a, $b): void { $this->assertSame($a, $b); } /** * @testdox assertNotSame($a, $b) * @dataProvider notSameProvider * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testAssertSameFails($a, $b): void { $this->expectException(AssertionFailedError::class); $this->assertSame($a, $b); } /** * @testdox assertSame($a, $b) fails * @dataProvider notSameProvider * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testAssertNotSameSucceeds($a, $b): void { $this->assertNotSame($a, $b); } /** * @testdox assertSame($a, $b) * @dataProvider sameProvider * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testAssertNotSameFails($a, $b): void { $this->expectException(AssertionFailedError::class); $this->assertNotSame($a, $b); } public function testAssertXmlFileEqualsXmlFile(): void { $this->assertXmlFileEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', TEST_FILES_PATH . 'foo.xml' ); $this->expectException(AssertionFailedError::class); $this->assertXmlFileEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', TEST_FILES_PATH . 'bar.xml' ); } public function testAssertXmlFileNotEqualsXmlFile(): void { $this->assertXmlFileNotEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', TEST_FILES_PATH . 'bar.xml' ); $this->expectException(AssertionFailedError::class); $this->assertXmlFileNotEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', TEST_FILES_PATH . 'foo.xml' ); } public function testAssertXmlStringEqualsXmlFile(): void { $this->assertXmlStringEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', \file_get_contents(TEST_FILES_PATH . 'foo.xml') ); $this->expectException(AssertionFailedError::class); $this->assertXmlStringEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', \file_get_contents(TEST_FILES_PATH . 'bar.xml') ); } public function testXmlStringNotEqualsXmlFile(): void { $this->assertXmlStringNotEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', \file_get_contents(TEST_FILES_PATH . 'bar.xml') ); $this->expectException(AssertionFailedError::class); $this->assertXmlStringNotEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', \file_get_contents(TEST_FILES_PATH . 'foo.xml') ); } public function testAssertXmlStringEqualsXmlString(): void { $this->assertXmlStringEqualsXmlString('', ''); $this->expectException(AssertionFailedError::class); $this->assertXmlStringEqualsXmlString('', ''); } /** * @ticket 1860 */ public function testAssertXmlStringEqualsXmlString2(): void { $this->expectException(Exception::class); $this->assertXmlStringEqualsXmlString('', ''); } /** * @ticket 1860 */ public function testAssertXmlStringEqualsXmlString3(): void { $expected = << XML; $actual = << XML; $this->assertXmlStringEqualsXmlString($expected, $actual); } public function testAssertXmlStringNotEqualsXmlString(): void { $this->assertXmlStringNotEqualsXmlString('', ''); $this->expectException(AssertionFailedError::class); $this->assertXmlStringNotEqualsXmlString('', ''); } public function testXMLStructureIsSame(): void { $expected = new \DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); $actual = new \DOMDocument; $actual->load(TEST_FILES_PATH . 'structureExpected.xml'); $this->assertEqualXMLStructure( $expected->firstChild, $actual->firstChild, true ); } public function testXMLStructureWrongNumberOfAttributes(): void { $expected = new \DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); $actual = new \DOMDocument; $actual->load(TEST_FILES_PATH . 'structureWrongNumberOfAttributes.xml'); $this->expectException(ExpectationFailedException::class); $this->assertEqualXMLStructure( $expected->firstChild, $actual->firstChild, true ); } public function testXMLStructureWrongNumberOfNodes(): void { $expected = new \DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); $actual = new \DOMDocument; $actual->load(TEST_FILES_PATH . 'structureWrongNumberOfNodes.xml'); $this->expectException(ExpectationFailedException::class); $this->assertEqualXMLStructure( $expected->firstChild, $actual->firstChild, true ); } public function testXMLStructureIsSameButDataIsNot(): void { $expected = new \DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); $actual = new \DOMDocument; $actual->load(TEST_FILES_PATH . 'structureIsSameButDataIsNot.xml'); $this->assertEqualXMLStructure( $expected->firstChild, $actual->firstChild, true ); } public function testXMLStructureAttributesAreSameButValuesAreNot(): void { $expected = new \DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); $actual = new \DOMDocument; $actual->load(TEST_FILES_PATH . 'structureAttributesAreSameButValuesAreNot.xml'); $this->assertEqualXMLStructure( $expected->firstChild, $actual->firstChild, true ); } public function testXMLStructureIgnoreTextNodes(): void { $expected = new \DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); $actual = new \DOMDocument; $actual->load(TEST_FILES_PATH . 'structureIgnoreTextNodes.xml'); $this->assertEqualXMLStructure( $expected->firstChild, $actual->firstChild, true ); } public function testAssertStringEqualsNumeric(): void { $this->assertEquals('0', 0); $this->expectException(AssertionFailedError::class); $this->assertEquals('0', 1); } public function testAssertStringEqualsNumeric2(): void { $this->assertNotEquals('A', 0); } public function testAssertIsReadable(): void { $this->assertIsReadable(__FILE__); $this->expectException(AssertionFailedError::class); $this->assertIsReadable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertNotIsReadable(): void { $this->assertNotIsReadable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); $this->expectException(AssertionFailedError::class); $this->assertNotIsReadable(__FILE__); } public function testAssertIsWritable(): void { $this->assertIsWritable(__FILE__); $this->expectException(AssertionFailedError::class); $this->assertIsWritable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertNotIsWritable(): void { $this->assertNotIsWritable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); $this->expectException(AssertionFailedError::class); $this->assertNotIsWritable(__FILE__); } public function testAssertDirectoryExists(): void { $this->assertDirectoryExists(__DIR__); $this->expectException(AssertionFailedError::class); $this->assertDirectoryExists(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertDirectoryNotExists(): void { $this->assertDirectoryNotExists(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); $this->expectException(AssertionFailedError::class); $this->assertDirectoryNotExists(__DIR__); } public function testAssertDirectoryIsReadable(): void { $this->assertDirectoryIsReadable(__DIR__); $this->expectException(AssertionFailedError::class); $this->assertDirectoryIsReadable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertDirectoryIsWritable(): void { $this->assertDirectoryIsWritable(__DIR__); $this->expectException(AssertionFailedError::class); $this->assertDirectoryIsWritable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertFileExists(): void { $this->assertFileExists(__FILE__); $this->expectException(AssertionFailedError::class); $this->assertFileExists(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertFileNotExists(): void { $this->assertFileNotExists(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); $this->expectException(AssertionFailedError::class); $this->assertFileNotExists(__FILE__); } public function testAssertFileIsReadable(): void { $this->assertFileIsReadable(__FILE__); $this->expectException(AssertionFailedError::class); $this->assertFileIsReadable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertFileIsNotReadable(): void { $tempFile = \tempnam( \sys_get_temp_dir(), 'unreadable' ); \chmod($tempFile, \octdec('0')); $this->assertFileNotIsReadable($tempFile); \chmod($tempFile, \octdec('755')); try { $this->assertFileNotIsReadable($tempFile); } catch (AssertionFailedError $e) { } \unlink($tempFile); } public function testAssertFileIsWritable(): void { $this->assertFileIsWritable(__FILE__); $this->expectException(AssertionFailedError::class); $this->assertFileIsWritable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertObjectHasAttribute(): void { $o = new \Author('Terry Pratchett'); $this->assertObjectHasAttribute('name', $o); $this->expectException(AssertionFailedError::class); $this->assertObjectHasAttribute('foo', $o); } public function testAssertObjectHasAttributeNumericAttribute(): void { $object = new \stdClass; $object->{'2020'} = 'Tokyo'; $this->assertObjectHasAttribute('2020', $object); $this->expectException(AssertionFailedError::class); $this->assertObjectHasAttribute('2018', $object); } public function testAssertObjectHasAttributeMultiByteAttribute(): void { $object = new \stdClass; $object->{'東京'} = 2020; $this->assertObjectHasAttribute('東京', $object); $this->expectException(AssertionFailedError::class); $this->assertObjectHasAttribute('長野', $object); } public function testAssertObjectNotHasAttribute(): void { $o = new \Author('Terry Pratchett'); $this->assertObjectNotHasAttribute('foo', $o); $this->expectException(AssertionFailedError::class); $this->assertObjectNotHasAttribute('name', $o); } public function testAssertObjectNotHasAttributeNumericAttribute(): void { $object = new \stdClass; $object->{'2020'} = 'Tokyo'; $this->assertObjectNotHasAttribute('2018', $object); $this->expectException(AssertionFailedError::class); $this->assertObjectNotHasAttribute('2020', $object); } public function testAssertObjectNotHasAttributeMultiByteAttribute(): void { $object = new \stdClass; $object->{'東京'} = 2020; $this->assertObjectNotHasAttribute('長野', $object); $this->expectException(AssertionFailedError::class); $this->assertObjectNotHasAttribute('東京', $object); } public function testAssertFinite(): void { $this->assertFinite(1); $this->expectException(AssertionFailedError::class); $this->assertFinite(\INF); } public function testAssertInfinite(): void { $this->assertInfinite(\INF); $this->expectException(AssertionFailedError::class); $this->assertInfinite(1); } public function testAssertNan(): void { $this->assertNan(\NAN); $this->expectException(AssertionFailedError::class); $this->assertNan(1); } public function testAssertNull(): void { $this->assertNull(null); $this->expectException(AssertionFailedError::class); $this->assertNull(new \stdClass); } public function testAssertNotNull(): void { $this->assertNotNull(new \stdClass); $this->expectException(AssertionFailedError::class); $this->assertNotNull(null); } public function testAssertTrue(): void { $this->assertTrue(true); $this->expectException(AssertionFailedError::class); $this->assertTrue(false); } public function testAssertNotTrue(): void { $this->assertNotTrue(false); $this->assertNotTrue(1); $this->assertNotTrue('true'); $this->expectException(AssertionFailedError::class); $this->assertNotTrue(true); } public function testAssertFalse(): void { $this->assertFalse(false); $this->expectException(AssertionFailedError::class); $this->assertFalse(true); } public function testAssertNotFalse(): void { $this->assertNotFalse(true); $this->assertNotFalse(0); $this->assertNotFalse(''); $this->expectException(AssertionFailedError::class); $this->assertNotFalse(false); } public function testAssertRegExp(): void { $this->assertRegExp('/foo/', 'foobar'); $this->expectException(AssertionFailedError::class); $this->assertRegExp('/foo/', 'bar'); } public function testAssertNotRegExp(): void { $this->assertNotRegExp('/foo/', 'bar'); $this->expectException(AssertionFailedError::class); $this->assertNotRegExp('/foo/', 'foobar'); } public function testAssertSame(): void { $o = new \stdClass; $this->assertSame($o, $o); $this->expectException(AssertionFailedError::class); $this->assertSame(new \stdClass, new \stdClass); } public function testAssertSame2(): void { $this->assertSame(true, true); $this->assertSame(false, false); $this->expectException(AssertionFailedError::class); $this->assertSame(true, false); } public function testAssertNotSame(): void { $this->assertNotSame( new \stdClass, null ); $this->assertNotSame( null, new \stdClass ); $this->assertNotSame( new \stdClass, new \stdClass ); $o = new \stdClass; $this->expectException(AssertionFailedError::class); $this->assertNotSame($o, $o); } public function testAssertNotSame2(): void { $this->assertNotSame(true, false); $this->assertNotSame(false, true); $this->expectException(AssertionFailedError::class); $this->assertNotSame(true, true); } public function testAssertNotSameFailsNull(): void { $this->expectException(AssertionFailedError::class); $this->assertNotSame(null, null); } public function testGreaterThan(): void { $this->assertGreaterThan(1, 2); $this->expectException(AssertionFailedError::class); $this->assertGreaterThan(2, 1); } public function testGreaterThanOrEqual(): void { $this->assertGreaterThanOrEqual(1, 2); $this->expectException(AssertionFailedError::class); $this->assertGreaterThanOrEqual(2, 1); } public function testLessThan(): void { $this->assertLessThan(2, 1); try { $this->assertLessThan(1, 2); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testLessThanOrEqual(): void { $this->assertLessThanOrEqual(2, 1); $this->expectException(AssertionFailedError::class); $this->assertLessThanOrEqual(1, 2); } public function testAssertClassHasAttributeThrowsExceptionIfAttributeNameIsNotValid(): void { $this->expectException(Exception::class); $this->assertClassHasAttribute('1', \ClassWithNonPublicAttributes::class); } public function testAssertClassHasAttributeThrowsExceptionIfClassDoesNotExist(): void { $this->expectException(Exception::class); $this->assertClassHasAttribute('attribute', 'ClassThatDoesNotExist'); } public function testAssertClassNotHasAttributeThrowsExceptionIfAttributeNameIsNotValid(): void { $this->expectException(Exception::class); $this->assertClassNotHasAttribute('1', \ClassWithNonPublicAttributes::class); } public function testAssertClassNotHasAttributeThrowsExceptionIfClassDoesNotExist(): void { $this->expectException(Exception::class); $this->assertClassNotHasAttribute('attribute', 'ClassThatDoesNotExist'); } public function testAssertClassHasStaticAttributeThrowsExceptionIfAttributeNameIsNotValid(): void { $this->expectException(Exception::class); $this->assertClassHasStaticAttribute('1', \ClassWithNonPublicAttributes::class); } public function testAssertClassHasStaticAttributeThrowsExceptionIfClassDoesNotExist(): void { $this->expectException(Exception::class); $this->assertClassHasStaticAttribute('attribute', 'ClassThatDoesNotExist'); } public function testAssertClassNotHasStaticAttributeThrowsExceptionIfAttributeNameIsNotValid(): void { $this->expectException(Exception::class); $this->assertClassNotHasStaticAttribute('1', \ClassWithNonPublicAttributes::class); } public function testAssertClassNotHasStaticAttributeThrowsExceptionIfClassDoesNotExist(): void { $this->expectException(Exception::class); $this->assertClassNotHasStaticAttribute('attribute', 'ClassThatDoesNotExist'); } public function testAssertObjectHasAttributeThrowsException2(): void { $this->expectException(Exception::class); $this->assertObjectHasAttribute('foo', null); } public function testAssertObjectHasAttributeThrowsExceptionIfAttributeNameIsNotValid(): void { $this->expectException(Exception::class); $this->assertObjectHasAttribute('1', \ClassWithNonPublicAttributes::class); } public function testAssertObjectNotHasAttributeThrowsException2(): void { $this->expectException(Exception::class); $this->assertObjectNotHasAttribute('foo', null); } public function testAssertObjectNotHasAttributeThrowsExceptionIfAttributeNameIsNotValid(): void { $this->expectException(Exception::class); $this->assertObjectNotHasAttribute('1', \ClassWithNonPublicAttributes::class); } public function testClassHasPublicAttribute(): void { $this->assertClassHasAttribute('publicAttribute', \ClassWithNonPublicAttributes::class); $this->expectException(AssertionFailedError::class); $this->assertClassHasAttribute('attribute', \ClassWithNonPublicAttributes::class); } public function testClassNotHasPublicAttribute(): void { $this->assertClassNotHasAttribute('attribute', \ClassWithNonPublicAttributes::class); $this->expectException(AssertionFailedError::class); $this->assertClassNotHasAttribute('publicAttribute', \ClassWithNonPublicAttributes::class); } public function testClassHasPublicStaticAttribute(): void { $this->assertClassHasStaticAttribute('publicStaticAttribute', \ClassWithNonPublicAttributes::class); $this->expectException(AssertionFailedError::class); $this->assertClassHasStaticAttribute('attribute', \ClassWithNonPublicAttributes::class); } public function testClassNotHasPublicStaticAttribute(): void { $this->assertClassNotHasStaticAttribute('attribute', \ClassWithNonPublicAttributes::class); $this->expectException(AssertionFailedError::class); $this->assertClassNotHasStaticAttribute('publicStaticAttribute', \ClassWithNonPublicAttributes::class); } public function testObjectHasPublicAttribute(): void { $obj = new \ClassWithNonPublicAttributes; $this->assertObjectHasAttribute('publicAttribute', $obj); $this->expectException(AssertionFailedError::class); $this->assertObjectHasAttribute('attribute', $obj); } public function testObjectNotHasPublicAttribute(): void { $obj = new \ClassWithNonPublicAttributes; $this->assertObjectNotHasAttribute('attribute', $obj); $this->expectException(AssertionFailedError::class); $this->assertObjectNotHasAttribute('publicAttribute', $obj); } public function testObjectHasOnTheFlyAttribute(): void { $obj = new \stdClass; $obj->foo = 'bar'; $this->assertObjectHasAttribute('foo', $obj); $this->expectException(AssertionFailedError::class); $this->assertObjectHasAttribute('bar', $obj); } public function testObjectNotHasOnTheFlyAttribute(): void { $obj = new \stdClass; $obj->foo = 'bar'; $this->assertObjectNotHasAttribute('bar', $obj); $this->expectException(AssertionFailedError::class); $this->assertObjectNotHasAttribute('foo', $obj); } public function testObjectHasProtectedAttribute(): void { $obj = new \ClassWithNonPublicAttributes; $this->assertObjectHasAttribute('protectedAttribute', $obj); $this->expectException(AssertionFailedError::class); $this->assertObjectHasAttribute('attribute', $obj); } public function testObjectNotHasProtectedAttribute(): void { $obj = new \ClassWithNonPublicAttributes; $this->assertObjectNotHasAttribute('attribute', $obj); $this->expectException(AssertionFailedError::class); $this->assertObjectNotHasAttribute('protectedAttribute', $obj); } public function testObjectHasPrivateAttribute(): void { $obj = new \ClassWithNonPublicAttributes; $this->assertObjectHasAttribute('privateAttribute', $obj); $this->expectException(AssertionFailedError::class); $this->assertObjectHasAttribute('attribute', $obj); } public function testObjectNotHasPrivateAttribute(): void { $obj = new \ClassWithNonPublicAttributes; $this->assertObjectNotHasAttribute('attribute', $obj); $this->expectException(AssertionFailedError::class); $this->assertObjectNotHasAttribute('privateAttribute', $obj); } /** * @doesNotPerformAssertions */ public function testAssertThatAnything(): void { $this->assertThat('anything', $this->anything()); } public function testAssertThatIsTrue(): void { $this->assertThat(true, $this->isTrue()); } public function testAssertThatIsFalse(): void { $this->assertThat(false, $this->isFalse()); } public function testAssertThatIsJson(): void { $this->assertThat('{}', $this->isJson()); } /** * @doesNotPerformAssertions */ public function testAssertThatAnythingAndAnything(): void { $this->assertThat( 'anything', $this->logicalAnd( $this->anything(), $this->anything() ) ); } /** * @doesNotPerformAssertions */ public function testAssertThatAnythingOrAnything(): void { $this->assertThat( 'anything', $this->logicalOr( $this->anything(), $this->anything() ) ); } /** * @doesNotPerformAssertions */ public function testAssertThatAnythingXorNotAnything(): void { $this->assertThat( 'anything', $this->logicalXor( $this->anything(), $this->logicalNot($this->anything()) ) ); } public function testAssertThatContains(): void { $this->assertThat(['foo'], $this->contains('foo')); } public function testAssertThatStringContains(): void { $this->assertThat('barfoobar', $this->stringContains('foo')); } public function testAssertThatContainsOnly(): void { $this->assertThat(['foo'], $this->containsOnly('string')); } public function testAssertThatContainsOnlyInstancesOf(): void { $this->assertThat([new \Book], $this->containsOnlyInstancesOf(\Book::class)); } public function testAssertThatArrayHasKey(): void { $this->assertThat(['foo' => 'bar'], $this->arrayHasKey('foo')); } public function testAssertThatClassHasAttribute(): void { $this->assertThat( new \ClassWithNonPublicAttributes, $this->classHasAttribute('publicAttribute') ); } public function testAssertThatClassHasStaticAttribute(): void { $this->assertThat( new \ClassWithNonPublicAttributes, $this->classHasStaticAttribute('publicStaticAttribute') ); } public function testAssertThatObjectHasAttribute(): void { $this->assertThat( new \ClassWithNonPublicAttributes, $this->objectHasAttribute('publicAttribute') ); } public function testAssertThatEqualTo(): void { $this->assertThat('foo', $this->equalTo('foo')); } public function testAssertThatIdenticalTo(): void { $value = new \stdClass; $constraint = $this->identicalTo($value); $this->assertThat($value, $constraint); } public function testAssertThatIsInstanceOf(): void { $this->assertThat(new \stdClass, $this->isInstanceOf('StdClass')); } public function testAssertThatIsType(): void { $this->assertThat('string', $this->isType('string')); } public function testAssertThatIsEmpty(): void { $this->assertThat([], $this->isEmpty()); } public function testAssertThatFileExists(): void { $this->assertThat(__FILE__, $this->fileExists()); } public function testAssertThatGreaterThan(): void { $this->assertThat(2, $this->greaterThan(1)); } public function testAssertThatGreaterThanOrEqual(): void { $this->assertThat(2, $this->greaterThanOrEqual(1)); } public function testAssertThatLessThan(): void { $this->assertThat(1, $this->lessThan(2)); } public function testAssertThatLessThanOrEqual(): void { $this->assertThat(1, $this->lessThanOrEqual(2)); } public function testAssertThatMatchesRegularExpression(): void { $this->assertThat('foobar', $this->matchesRegularExpression('/foo/')); } public function testAssertThatCallback(): void { $this->assertThat( null, $this->callback(function ($other) { return true; }) ); } public function testAssertThatCountOf(): void { $this->assertThat([1], $this->countOf(1)); } public function testAssertFileEquals(): void { $this->assertFileEquals( TEST_FILES_PATH . 'foo.xml', TEST_FILES_PATH . 'foo.xml' ); $this->expectException(AssertionFailedError::class); $this->assertFileEquals( TEST_FILES_PATH . 'foo.xml', TEST_FILES_PATH . 'bar.xml' ); } public function testAssertFileNotEquals(): void { $this->assertFileNotEquals( TEST_FILES_PATH . 'foo.xml', TEST_FILES_PATH . 'bar.xml' ); $this->expectException(AssertionFailedError::class); $this->assertFileNotEquals( TEST_FILES_PATH . 'foo.xml', TEST_FILES_PATH . 'foo.xml' ); } public function testAssertStringEqualsFile(): void { $this->assertStringEqualsFile( TEST_FILES_PATH . 'foo.xml', \file_get_contents(TEST_FILES_PATH . 'foo.xml') ); $this->expectException(AssertionFailedError::class); $this->assertStringEqualsFile( TEST_FILES_PATH . 'foo.xml', \file_get_contents(TEST_FILES_PATH . 'bar.xml') ); } public function testAssertStringNotEqualsFile(): void { $this->assertStringNotEqualsFile( TEST_FILES_PATH . 'foo.xml', \file_get_contents(TEST_FILES_PATH . 'bar.xml') ); $this->expectException(AssertionFailedError::class); $this->assertStringNotEqualsFile( TEST_FILES_PATH . 'foo.xml', \file_get_contents(TEST_FILES_PATH . 'foo.xml') ); } public function testAssertFileEqualsIgnoringCase(): void { $this->assertFileEqualsIgnoringCase( TEST_FILES_PATH . 'foo.xml', TEST_FILES_PATH . 'fooUppercase.xml' ); $this->expectException(AssertionFailedError::class); $this->assertFileEqualsIgnoringCase( TEST_FILES_PATH . 'foo.xml', TEST_FILES_PATH . 'bar.xml' ); } public function testAssertStringStartsNotWithThrowsException2(): void { $this->expectException(Exception::class); $this->assertStringStartsNotWith('', null); } public function testAssertStringStartsWith(): void { $this->assertStringStartsWith('prefix', 'prefixfoo'); $this->expectException(AssertionFailedError::class); $this->assertStringStartsWith('prefix', 'foo'); } public function testAssertStringStartsNotWith(): void { $this->assertStringStartsNotWith('prefix', 'foo'); $this->expectException(AssertionFailedError::class); $this->assertStringStartsNotWith('prefix', 'prefixfoo'); } public function testAssertStringEndsWith(): void { $this->assertStringEndsWith('suffix', 'foosuffix'); $this->expectException(AssertionFailedError::class); $this->assertStringEndsWith('suffix', 'foo'); } public function testAssertStringEndsNotWith(): void { $this->assertStringEndsNotWith('suffix', 'foo'); $this->expectException(AssertionFailedError::class); $this->assertStringEndsNotWith('suffix', 'foosuffix'); } public function testAssertStringMatchesFormat(): void { $this->assertStringMatchesFormat('*%s*', '***'); } public function testAssertStringMatchesFormatFailure(): void { $this->expectException(AssertionFailedError::class); $this->assertStringMatchesFormat('*%s*', '**'); } public function testAssertStringNotMatchesFormat(): void { $this->assertStringNotMatchesFormat('*%s*', '**'); $this->expectException(AssertionFailedError::class); $this->assertStringMatchesFormat('*%s*', '**'); } public function testAssertEmpty(): void { $this->assertEmpty([]); $this->expectException(AssertionFailedError::class); $this->assertEmpty(['foo']); } public function testAssertNotEmpty(): void { $this->assertNotEmpty(['foo']); $this->expectException(AssertionFailedError::class); $this->assertNotEmpty([]); } public function testMarkTestIncomplete(): void { try { $this->markTestIncomplete('incomplete'); } catch (IncompleteTestError $e) { $this->assertEquals('incomplete', $e->getMessage()); return; } $this->fail(); } public function testMarkTestSkipped(): void { try { $this->markTestSkipped('skipped'); } catch (SkippedTestError $e) { $this->assertEquals('skipped', $e->getMessage()); return; } $this->fail(); } public function testAssertCount(): void { $this->assertCount(2, [1, 2]); $this->expectException(AssertionFailedError::class); $this->assertCount(2, [1, 2, 3]); } public function testAssertCountTraversable(): void { $this->assertCount(2, new \ArrayIterator([1, 2])); $this->expectException(AssertionFailedError::class); $this->assertCount(2, new \ArrayIterator([1, 2, 3])); } public function testAssertCountThrowsExceptionIfElementIsNotCountable(): void { try { $this->assertCount(2, ''); } catch (Exception $e) { $this->assertEquals('Argument #2 of PHPUnit\Framework\Assert::assertCount() must be a countable or iterable', $e->getMessage()); return; } $this->fail(); } public function testAssertNotCount(): void { $this->assertNotCount(2, [1, 2, 3]); $this->expectException(AssertionFailedError::class); $this->assertNotCount(2, [1, 2]); } public function testAssertNotCountThrowsExceptionIfElementIsNotCountable(): void { $this->expectException(Exception::class); $this->assertNotCount(2, ''); } public function testAssertSameSize(): void { $this->assertSameSize([1, 2], [3, 4]); $this->expectException(AssertionFailedError::class); $this->assertSameSize([1, 2], [1, 2, 3]); } public function testAssertSameSizeThrowsExceptionIfExpectedIsNotCountable(): void { try { $this->assertSameSize('a', []); } catch (Exception $e) { $this->assertEquals('Argument #1 of PHPUnit\Framework\Assert::assertSameSize() must be a countable or iterable', $e->getMessage()); return; } $this->fail(); } public function testAssertSameSizeThrowsExceptionIfActualIsNotCountable(): void { try { $this->assertSameSize([], ''); } catch (Exception $e) { $this->assertEquals('Argument #2 of PHPUnit\Framework\Assert::assertSameSize() must be a countable or iterable', $e->getMessage()); return; } $this->fail(); } public function testAssertNotSameSize(): void { $this->assertNotSameSize([1, 2], [1, 2, 3]); $this->expectException(AssertionFailedError::class); $this->assertNotSameSize([1, 2], [3, 4]); } public function testAssertNotSameSizeThrowsExceptionIfExpectedIsNotCountable(): void { $this->expectException(Exception::class); $this->assertNotSameSize('a', []); } public function testAssertNotSameSizeThrowsExceptionIfActualIsNotCountable(): void { $this->expectException(Exception::class); $this->assertNotSameSize([], ''); } /** * @testdox Assert JSON */ public function testAssertJson(): void { $this->assertJson('{}'); } /** * @testdox Assert JSON string equals JSON string */ public function testAssertJsonStringEqualsJsonString(): void { $expected = '{"Mascott" : "Tux"}'; $actual = '{"Mascott" : "Tux"}'; $message = 'Given Json strings do not match'; $this->assertJsonStringEqualsJsonString($expected, $actual, $message); } /** * @dataProvider validInvalidJsonDataprovider * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testAssertJsonStringEqualsJsonStringErrorRaised($expected, $actual): void { $this->expectException(AssertionFailedError::class); $this->assertJsonStringEqualsJsonString($expected, $actual); } public function testAssertJsonStringNotEqualsJsonString(): void { $expected = '{"Mascott" : "Beastie"}'; $actual = '{"Mascott" : "Tux"}'; $message = 'Given Json strings do match'; $this->assertJsonStringNotEqualsJsonString($expected, $actual, $message); } /** * @testdox Assert JSON string equals equals JSON string raised $_dataName * @dataProvider validInvalidJsonDataprovider * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testAssertJsonStringNotEqualsJsonStringErrorRaised($expected, $actual): void { $this->expectException(AssertionFailedError::class); $this->assertJsonStringNotEqualsJsonString($expected, $actual); } public function testAssertJsonStringEqualsJsonFile(): void { $file = TEST_FILES_PATH . 'JsonData/simpleObject.json'; $actual = \json_encode(['Mascott' => 'Tux']); $message = ''; $this->assertJsonStringEqualsJsonFile($file, $actual, $message); } public function testAssertJsonStringEqualsJsonFileExpectingExpectationFailedException(): void { $file = TEST_FILES_PATH . 'JsonData/simpleObject.json'; $actual = \json_encode(['Mascott' => 'Beastie']); $message = ''; try { $this->assertJsonStringEqualsJsonFile($file, $actual, $message); } catch (ExpectationFailedException $e) { $this->assertEquals( 'Failed asserting that \'{"Mascott":"Beastie"}\' matches JSON string "{"Mascott":"Tux"}".', $e->getMessage() ); return; } $this->fail('Expected Exception not thrown.'); } public function testAssertJsonStringNotEqualsJsonFile(): void { $file = TEST_FILES_PATH . 'JsonData/simpleObject.json'; $actual = \json_encode(['Mascott' => 'Beastie']); $message = ''; $this->assertJsonStringNotEqualsJsonFile($file, $actual, $message); } public function testAssertJsonFileNotEqualsJsonFile(): void { $fileExpected = TEST_FILES_PATH . 'JsonData/simpleObject.json'; $fileActual = TEST_FILES_PATH . 'JsonData/arrayObject.json'; $message = ''; $this->assertJsonFileNotEqualsJsonFile($fileExpected, $fileActual, $message); } public function testAssertJsonFileEqualsJsonFile(): void { $file = TEST_FILES_PATH . 'JsonData/simpleObject.json'; $message = ''; $this->assertJsonFileEqualsJsonFile($file, $file, $message); } public function testAssertInstanceOfThrowsExceptionIfTypeDoesNotExist(): void { $this->expectException(Exception::class); $this->assertInstanceOf('ClassThatDoesNotExist', new \stdClass); } public function testAssertInstanceOf(): void { $this->assertInstanceOf(\stdClass::class, new \stdClass); $this->expectException(AssertionFailedError::class); $this->assertInstanceOf(\Exception::class, new \stdClass); } public function testAssertNotInstanceOfThrowsExceptionIfTypeDoesNotExist(): void { $this->expectException(Exception::class); $this->assertNotInstanceOf('ClassThatDoesNotExist', new \stdClass); } public function testAssertNotInstanceOf(): void { $this->assertNotInstanceOf(\Exception::class, new \stdClass); $this->expectException(AssertionFailedError::class); $this->assertNotInstanceOf(\stdClass::class, new \stdClass); } public function testAssertStringMatchesFormatFileThrowsExceptionForInvalidArgument(): void { $this->expectException(Exception::class); $this->assertStringMatchesFormatFile('not_existing_file', ''); } public function testAssertStringMatchesFormatFile(): void { $this->assertStringMatchesFormatFile(TEST_FILES_PATH . 'expectedFileFormat.txt', "FOO\n"); $this->expectException(AssertionFailedError::class); $this->assertStringMatchesFormatFile(TEST_FILES_PATH . 'expectedFileFormat.txt', "BAR\n"); } public function testAssertStringNotMatchesFormatFileThrowsExceptionForInvalidArgument(): void { $this->expectException(Exception::class); $this->assertStringNotMatchesFormatFile('not_existing_file', ''); } public function testAssertStringNotMatchesFormatFile(): void { $this->assertStringNotMatchesFormatFile(TEST_FILES_PATH . 'expectedFileFormat.txt', "BAR\n"); $this->expectException(AssertionFailedError::class); $this->assertStringNotMatchesFormatFile(TEST_FILES_PATH . 'expectedFileFormat.txt', "FOO\n"); } public function testStringsCanBeComparedForEqualityIgnoringCase(): void { $this->assertEqualsIgnoringCase('a', 'A'); $this->assertNotEqualsIgnoringCase('a', 'B'); } public function testArraysOfStringsCanBeComparedForEqualityIgnoringCase(): void { $this->assertEqualsIgnoringCase(['a'], ['A']); $this->assertNotEqualsIgnoringCase(['a'], ['B']); } public function testStringsCanBeComparedForEqualityWithDelta(): void { $this->assertEqualsWithDelta(2.3, 2.5, 0.5); $this->assertNotEqualsWithDelta(2.3, 3.5, 0.5); } public function testArraysOfStringsCanBeComparedForEqualityWithDelta(): void { $this->assertEqualsWithDelta([2.3], [2.5], 0.5); $this->assertNotEqualsWithDelta([2.3], [3.5], 0.5); } public function testArraysCanBeComparedForEqualityWithCanonicalization(): void { $this->assertEqualsCanonicalizing([3, 2, 1], [2, 3, 1]); $this->assertNotEqualsCanonicalizing([3, 2, 1], [2, 3, 4]); } public function testArrayTypeCanBeAsserted(): void { $this->assertIsArray([]); try { $this->assertIsArray(null); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testBoolTypeCanBeAsserted(): void { $this->assertIsBool(true); try { $this->assertIsBool(null); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testFloatTypeCanBeAsserted(): void { $this->assertIsFloat(0.0); try { $this->assertIsFloat(null); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testIntTypeCanBeAsserted(): void { $this->assertIsInt(1); try { $this->assertIsInt(null); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNumericTypeCanBeAsserted(): void { $this->assertIsNumeric('1.0'); try { $this->assertIsNumeric('abc'); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testObjectTypeCanBeAsserted(): void { $this->assertIsObject(new \stdClass); try { $this->assertIsObject(null); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testResourceTypeCanBeAsserted(): void { $this->assertIsResource(\fopen(__FILE__, 'r')); try { $this->assertIsResource(null); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testStringTypeCanBeAsserted(): void { $this->assertIsString(''); try { $this->assertIsString(null); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testScalarTypeCanBeAsserted(): void { $this->assertIsScalar(true); try { $this->assertIsScalar(new \stdClass); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testCallableTypeCanBeAsserted(): void { $this->assertIsCallable(function (): void { }); try { $this->assertIsCallable(null); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testIterableTypeCanBeAsserted(): void { $this->assertIsIterable([]); try { $this->assertIsIterable(null); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNotArrayTypeCanBeAsserted(): void { $this->assertIsNotArray(null); try { $this->assertIsNotArray([]); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNotBoolTypeCanBeAsserted(): void { $this->assertIsNotBool(null); try { $this->assertIsNotBool(true); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNotFloatTypeCanBeAsserted(): void { $this->assertIsNotFloat(null); try { $this->assertIsNotFloat(0.0); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNotIntTypeCanBeAsserted(): void { $this->assertIsNotInt(null); try { $this->assertIsNotInt(1); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNotNumericTypeCanBeAsserted(): void { $this->assertIsNotNumeric('abc'); try { $this->assertIsNotNumeric('1.0'); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNotObjectTypeCanBeAsserted(): void { $this->assertIsNotObject(null); try { $this->assertIsNotObject(new \stdClass); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNotResourceTypeCanBeAsserted(): void { $this->assertIsNotResource(null); try { $this->assertIsNotResource(\fopen(__FILE__, 'r')); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNotScalarTypeCanBeAsserted(): void { $this->assertIsNotScalar(new \stdClass); try { $this->assertIsNotScalar(true); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNotStringTypeCanBeAsserted(): void { $this->assertIsNotString(null); try { $this->assertIsNotString(''); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNotCallableTypeCanBeAsserted(): void { $this->assertIsNotCallable(null); try { $this->assertIsNotCallable(function (): void { }); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testNotIterableTypeCanBeAsserted(): void { $this->assertIsNotIterable(null); try { $this->assertIsNotIterable([]); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testLogicalAnd(): void { $this->assertThat( true, $this->logicalAnd( $this->isTrue(), $this->isTrue() ) ); $this->expectException(AssertionFailedError::class); $this->assertThat( true, $this->logicalAnd( $this->isTrue(), $this->isFalse() ) ); } public function testLogicalOr(): void { $this->assertThat( true, $this->logicalOr( $this->isTrue(), $this->isFalse() ) ); $this->expectException(AssertionFailedError::class); $this->assertThat( true, $this->logicalOr( $this->isFalse(), $this->isFalse() ) ); } public function testLogicalXor(): void { $this->assertThat( true, $this->logicalXor( $this->isTrue(), $this->isFalse() ) ); $this->expectException(AssertionFailedError::class); $this->assertThat( true, $this->logicalXor( $this->isTrue(), $this->isTrue() ) ); } public function testStringContainsStringCanBeAsserted(): void { $this->assertStringContainsString('bar', 'foobarbaz'); try { $this->assertStringContainsString('barbara', 'foobarbaz'); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testStringNotContainsStringCanBeAsserted(): void { $this->assertStringNotContainsString('barbara', 'foobarbaz'); try { $this->assertStringNotContainsString('bar', 'foobarbaz'); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testStringContainsStringCanBeAssertedIgnoringCase(): void { $this->assertStringContainsStringIgnoringCase('BAR', 'foobarbaz'); try { $this->assertStringContainsStringIgnoringCase('BARBARA', 'foobarbaz'); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testStringNotContainsStringCanBeAssertedIgnoringCase(): void { $this->assertStringNotContainsStringIgnoringCase('BARBARA', 'foobarbaz'); try { $this->assertStringNotContainsStringIgnoringCase('BAR', 'foobarbaz'); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testIterableContainsSameObjectCanBeAsserted(): void { $object = new \stdClass; $iterable = [$object]; $this->assertContains($object, $iterable); try { $this->assertContains(new \stdClass, $iterable); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testIterableNotContainsSameObjectCanBeAsserted(): void { $object = new \stdClass; $iterable = [$object]; $this->assertNotContains(new \stdClass, $iterable); try { $this->assertNotContains($object, $iterable); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testIterableContainsEqualObjectCanBeAsserted(): void { $a = new \stdClass; $a->foo = 'bar'; $b = new \stdClass; $b->foo = 'baz'; $this->assertContainsEquals($a, [$a]); try { $this->assertContainsEquals($b, [$a]); } catch (AssertionFailedError $e) { return; } $this->fail(); } public function testIterableNotContainsEqualObjectCanBeAsserted(): void { $a = new \stdClass; $a->foo = 'bar'; $b = new \stdClass; $b->foo = 'baz'; $this->assertNotContainsEquals($b, [$a]); try { $this->assertNotContainsEquals($a, [$a]); } catch (AssertionFailedError $e) { return; } $this->fail(); } protected function sameValues(): array { $object = new \SampleClass(4, 8, 15); $file = TEST_FILES_PATH . 'foo.xml'; $resource = \fopen($file, 'r'); return [ // null [null, null], // strings ['a', 'a'], // integers [0, 0], // floats [2.3, 2.3], [1 / 3, 1 - 2 / 3], [\log(0), \log(0)], // arrays [[], []], [[0 => 1], [0 => 1]], [[0 => null], [0 => null]], [['a', 'b' => [1, 2]], ['a', 'b' => [1, 2]]], // objects [$object, $object], // resources [$resource, $resource], ]; } protected function notEqualValues(): array { // cyclic dependencies $book1 = new \Book; $book1->author = new \Author('Terry Pratchett'); $book1->author->books[] = $book1; $book2 = new \Book; $book2->author = new \Author('Terry Pratch'); $book2->author->books[] = $book2; $book3 = new \Book; $book3->author = 'Terry Pratchett'; $book4 = new \stdClass; $book4->author = 'Terry Pratchett'; $object1 = new \SampleClass(4, 8, 15); $object2 = new \SampleClass(16, 23, 42); $object3 = new \SampleClass(4, 8, 15); $storage1 = new \SplObjectStorage; $storage1->attach($object1); $storage2 = new \SplObjectStorage; $storage2->attach($object3); // same content, different object $file = TEST_FILES_PATH . 'foo.xml'; return [ // strings ['a', 'b'], ['a', 'A'], // https://github.com/sebastianbergmann/phpunit/issues/1023 ['9E6666666', '9E7777777'], // integers [1, 2], [2, 1], // floats [2.3, 4.2], [2.3, 4.2, 0.5], [[2.3], [4.2], 0.5], [[[2.3]], [[4.2]], 0.5], [new \Struct(2.3), new \Struct(4.2), 0.5], [[new \Struct(2.3)], [new \Struct(4.2)], 0.5], // NAN [\NAN, \NAN], // arrays [[], [0 => 1]], [[0 => 1], []], [[0 => null], []], [[0 => 1, 1 => 2], [0 => 1, 1 => 3]], [['a', 'b' => [1, 2]], ['a', 'b' => [2, 1]]], // objects [new \SampleClass(4, 8, 15), new \SampleClass(16, 23, 42)], [$object1, $object2], [$book1, $book2], [$book3, $book4], // same content, different class // resources [\fopen($file, 'r'), \fopen($file, 'r')], // SplObjectStorage [$storage1, $storage2], // DOMDocument [ Xml::load(''), Xml::load(''), ], [ Xml::load(''), Xml::load(''), ], [ Xml::load(' bar '), Xml::load(''), ], [ Xml::load(''), Xml::load(''), ], [ Xml::load(' bar '), Xml::load(' bir '), ], [ new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-29 03:13:35', new \DateTimeZone('America/New_York')), ], [ new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-29 03:13:35', new \DateTimeZone('America/New_York')), 3500, ], [ new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-29 05:13:35', new \DateTimeZone('America/New_York')), 3500, ], [ new \DateTime('2013-03-29', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-30', new \DateTimeZone('America/New_York')), ], [ new \DateTime('2013-03-29', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-30', new \DateTimeZone('America/New_York')), 43200, ], [ new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/Chicago')), ], [ new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/Chicago')), 3500, ], [ new \DateTime('2013-03-30', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-30', new \DateTimeZone('America/Chicago')), ], [ new \DateTime('2013-03-29T05:13:35-0600'), new \DateTime('2013-03-29T04:13:35-0600'), ], [ new \DateTime('2013-03-29T05:13:35-0600'), new \DateTime('2013-03-29T05:13:35-0500'), ], // Exception //array(new Exception('Exception 1'), new Exception('Exception 2')), // different types [new \SampleClass(4, 8, 15), false], [false, new \SampleClass(4, 8, 15)], [[0 => 1, 1 => 2], false], [false, [0 => 1, 1 => 2]], [[], new \stdClass], [new \stdClass, []], // PHP: 0 == 'Foobar' => true! // We want these values to differ [0, 'Foobar'], ['Foobar', 0], [3, \acos(8)], [\acos(8), 3], ]; } protected function equalValues(): array { // cyclic dependencies $book1 = new \Book; $book1->author = new \Author('Terry Pratchett'); $book1->author->books[] = $book1; $book2 = new \Book; $book2->author = new \Author('Terry Pratchett'); $book2->author->books[] = $book2; $object1 = new \SampleClass(4, 8, 15); $object2 = new \SampleClass(4, 8, 15); $storage1 = new \SplObjectStorage; $storage1->attach($object1); $storage2 = new \SplObjectStorage; $storage2->attach($object1); return [ // arrays [['a' => 1, 'b' => 2], ['b' => 2, 'a' => 1]], [[1], ['1']], // objects [$object1, $object2], [$book1, $book2], // SplObjectStorage [$storage1, $storage2], // DOMDocument [ Xml::load(''), Xml::load(''), ], [ Xml::load(''), Xml::load(''), ], [ Xml::load(''), Xml::load(''), ], [ Xml::load("\n \n"), Xml::load(''), ], [ new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), ], [ new \DateTime('2013-03-29', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-29', new \DateTimeZone('America/New_York')), ], [ new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-29 03:13:35', new \DateTimeZone('America/Chicago')), ], [ new \DateTime('2013-03-30', new \DateTimeZone('America/New_York')), new \DateTime('2013-03-29 23:00:00', new \DateTimeZone('America/Chicago')), ], [ new \DateTime('@1364616000'), new \DateTime('2013-03-29 23:00:00', new \DateTimeZone('America/Chicago')), ], [ new \DateTime('2013-03-29T05:13:35-0500'), new \DateTime('2013-03-29T04:13:35-0600'), ], // Exception //array(new Exception('Exception 1'), new Exception('Exception 1')), // mixed types [0, '0'], ['0', 0], [2.3, '2.3'], ['2.3', 2.3], [(string) (1 / 3), 1 - 2 / 3], [1 / 3, (string) (1 - 2 / 3)], ['string representation', new \ClassWithToString], [new \ClassWithToString, 'string representation'], ]; } } PK!|اFramework/TestFailureTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use PHPUnit\Framework\Error\Error; use SebastianBergmann\Comparator\ComparisonFailure; /** * @small */ final class TestFailureTest extends TestCase { public function testToString(): void { $test = new self(__FUNCTION__); $exception = new Exception('message'); $failure = new TestFailure($test, $exception); $this->assertEquals(__METHOD__ . ': message', $failure->toString()); } public function testToStringForError(): void { $test = new self(__FUNCTION__); $exception = new \Error('message'); $failure = new TestFailure($test, $exception); $this->assertEquals(__METHOD__ . ': message', $failure->toString()); } public function testToStringForNonSelfDescribing(): void { $test = new \NotSelfDescribingTest(); $exception = new Exception('message'); $failure = new TestFailure($test, $exception); $this->assertEquals('NotSelfDescribingTest: message', $failure->toString()); } public function testgetExceptionAsString(): void { $test = new self(__FUNCTION__); $exception = new \Error('message'); $failure = new TestFailure($test, $exception); $this->assertEquals("Error: message\n", $failure->getExceptionAsString()); } public function testExceptionToString(): void { $exception = new AssertionFailedError('message'); $this->assertEquals("message\n", TestFailure::exceptionToString($exception)); } public function testExceptionToStringForExpectationFailedException(): void { $exception = new ExpectationFailedException('message'); $this->assertEquals("message\n", TestFailure::exceptionToString($exception)); } public function testExceptionToStringForExpectationFailedExceptionWithComparisonFailure(): void { $exception = new ExpectationFailedException('message', new ComparisonFailure('expected', 'actual', 'expected', 'actual')); $this->assertEquals("message\n--- Expected\n+++ Actual\n@@ @@\n-expected\n+actual\n", TestFailure::exceptionToString($exception)); } public function testExceptionToStringForFrameworkError(): void { $exception = new Error('message', 0, 'file', 1); $this->assertEquals("message\n", TestFailure::exceptionToString($exception)); } public function testExceptionToStringForExceptionWrapper(): void { $exception = new ExceptionWrapper(new \Error('message')); $this->assertEquals("Error: message\n", TestFailure::exceptionToString($exception)); } public function testGetTestName(): void { $test = new self(__FUNCTION__); $exception = new Exception('message'); $failure = new TestFailure($test, $exception); $this->assertEquals($this->toString(), $failure->getTestName()); } public function testFailedTest(): void { $test = new self(__FUNCTION__); $exception = new Exception('message'); $failure = new TestFailure($test, $exception); $this->assertEquals($test, $failure->failedTest()); } public function testThrownException(): void { $test = new self(__FUNCTION__); $exception = new Exception('message'); $failure = new TestFailure($test, $exception); $this->assertEquals($exception, $failure->thrownException()); } public function testExceptionMessage(): void { $test = new self(__FUNCTION__); $exception = new Exception('message'); $failure = new TestFailure($test, $exception); $this->assertEquals('message', $failure->exceptionMessage()); } public function testIsFailure(): void { $test = new self(__FUNCTION__); $exception = new ExpectationFailedException('message'); $failure = new TestFailure($test, $exception); $this->assertTrue($failure->isFailure()); } public function testIsFailureFalse(): void { $test = new self(__FUNCTION__); $exception = new Warning('message'); $failure = new TestFailure($test, $exception); $this->assertFalse($failure->isFailure()); } } PK!"Framework/Assert/FunctionsTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; final class FunctionsTest extends TestCase { private static $globalAssertionFunctions = []; public static function setUpBeforeClass(): void { \preg_match_all( '/function (assert[^ \(]+)/', \file_get_contents( __DIR__ . '/../../../../src/Framework/Assert/Functions.php' ), $matches ); self::$globalAssertionFunctions = $matches[1]; } /** * @dataProvider provideStaticAssertionMethodNames */ public function testGlobalFunctionsFileContainsAllStaticAssertions(string $methodName): void { Assert::assertContains( $methodName, self::$globalAssertionFunctions, "Mapping for Assert::$methodName is missing in Functions.php" ); } public function provideStaticAssertionMethodNames(): array { \preg_match_all( '/public static function (assert[^ \(]+)/', \file_get_contents( __DIR__ . '/../../../../src/Framework/Assert.php' ), $matches ); return \array_reduce( $matches[1], function (array $functionNames, string $functionName) { $functionNames[$functionName] = [$functionName]; return $functionNames; }, [] ); } } PK!B4<Framework/TestBuilderTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use PHPUnit\Framework\MockObject\MockObject; /** * @covers \PHPUnit\Framework\TestBuilder */ final class TestBuilderTest extends TestCase { public function testCreateTestForConstructorlessTestClass(): void { $reflector = $this->getMockBuilder(\ReflectionClass::class) ->setConstructorArgs([$this]) ->getMock(); \assert($reflector instanceof MockObject); \assert($reflector instanceof \ReflectionClass); $reflector->expects($this->once()) ->method('getConstructor') ->willReturn(null); $reflector->expects($this->once()) ->method('isInstantiable') ->willReturn(true); $reflector->expects($this->once()) ->method('getName') ->willReturn(__CLASS__); $this->expectException(Exception::class); $this->expectExceptionMessage('No valid test provided.'); (new TestBuilder)->build($reflector, 'TestForConstructorlessTestClass'); } public function testCreateTestForNotInstantiableTestClass(): void { $reflector = $this->getMockBuilder(\ReflectionClass::class) ->setConstructorArgs([$this]) ->getMock(); \assert($reflector instanceof MockObject); \assert($reflector instanceof \ReflectionClass); $reflector->expects($this->once()) ->method('isInstantiable') ->willReturn(false); $reflector->expects($this->once()) ->method('getName') ->willReturn('foo'); $test = (new TestBuilder)->build($reflector, 'TestForNonInstantiableTestClass'); $this->assertInstanceOf(WarningTestCase::class, $test); /* @var WarningTestCase $test */ $this->assertSame('Cannot instantiate class "foo".', $test->getMessage()); } public function testCreateTestForTestClassWithModifiedConstructor(): void { $test = (new TestBuilder)->build(new \ReflectionClass(\ModifiedConstructorTestCase::class), 'testCase'); $this->assertInstanceOf(\ModifiedConstructorTestCase::class, $test); } public function testCreateWithEmptyData(): void { $test = (new TestBuilder)->build(new \ReflectionClass(\EmptyDataProviderTest::class), 'testCase'); $this->assertInstanceOf(DataProviderTestSuite::class, $test); /* @var DataProviderTestSuite $test */ $this->assertInstanceOf(SkippedTestCase::class, $test->getGroupDetails()['default'][0]); } /** * @dataProvider provideWithAnnotations */ public function testWithAnnotations(string $methodName): void { $test = (new TestBuilder)->build(new \ReflectionClass(\TestWithAnnotations::class), $methodName); $this->assertInstanceOf(\TestWithAnnotations::class, $test); } public function provideWithAnnotations(): array { return [ ['testThatInteractsWithGlobalVariables'], ['testThatInteractsWithStaticAttributes'], ['testInSeparateProcess'], ]; } /** * @dataProvider provideWithAnnotationsAndDataProvider */ public function testWithAnnotationsAndDataProvider(string $methodName): void { $test = (new TestBuilder)->build(new \ReflectionClass(\TestWithAnnotations::class), $methodName); $this->assertInstanceOf(DataProviderTestSuite::class, $test); } public function provideWithAnnotationsAndDataProvider(): array { return [ ['testThatInteractsWithGlobalVariablesWithDataProvider'], ['testThatInteractsWithStaticAttributesWithDataProvider'], ['testInSeparateProcessWithDataProvider'], ]; } } PK!Whh4Framework/Exception/InvalidArgumentExceptionTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; /** * @small */ final class InvalidArgumentExceptionTest extends TestCase { /** * @dataProvider provider */ public function testUsesCorrectArticleInErrorMessage(string $expected, $type): void { $e = InvalidArgumentException::create(1, $type); $this->assertStringMatchesFormat($expected, $e->getMessage()); } public function provider(): array { return [ 'an array' => ['Argument #1 of %s must be an array', 'array'], 'a boolean' => ['Argument #1 of %s must be a boolean', 'boolean'], ]; } } PK! O%Framework/Exception/ExceptionTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; class ExceptionTest extends TestCase { public function testExceptionSleep(): void { $exception = new Exception(); $expectedArray = [ 'serializableTrace', 'message', 'code', 'file', 'line', ]; $this->assertSame($expectedArray, $exception->__sleep()); } } PK!j>"Framework/ExceptionWrapperTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; /** * @small */ final class ExceptionWrapperTest extends TestCase { /** * @runInSeparateProcess */ public function testGetOriginalException(): void { $e = new \BadFunctionCallException('custom class exception'); $wrapper = new ExceptionWrapper($e); $this->assertInstanceOf(\BadFunctionCallException::class, $wrapper->getOriginalException()); } /** * @runInSeparateProcess */ public function testGetOriginalExceptionWithPrevious(): void { $e = new \BadFunctionCallException('custom class exception', 0, new \Exception('previous')); $wrapper = new ExceptionWrapper($e); $this->assertInstanceOf(\BadFunctionCallException::class, $wrapper->getOriginalException()); } /** * @runInSeparateProcess */ public function testNoOriginalExceptionInStacktrace(): void { $e = new \BadFunctionCallException('custom class exception'); $wrapper = new ExceptionWrapper($e); // Replace the only mention of "BadFunctionCallException" in wrapper $wrapper->setClassName('MyException'); $data = \print_r($wrapper, true); $this->assertStringNotContainsString( 'BadFunctionCallException', $data, 'Assert there is s no other BadFunctionCallException mention in stacktrace' ); } } PK!]Xٴ!Framework/TestImplementorTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; /** * @small */ final class TestImplementorTest extends TestCase { public function testSuccessfulRun(): void { $result = new TestResult; $test = new \DoubleTestCase(new \Success); $test->run($result); $this->assertCount(\count($test), $result); $this->assertEquals(0, $result->errorCount()); $this->assertEquals(0, $result->failureCount()); } } PK!8M Util/Annotation/RegistryTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util\Annotation; use PHPUnit\Framework\TestCase; use PHPUnit\Util\Exception; /** * @small * * @covers \PHPUnit\Util\Annotation\Registry * * @uses \PHPUnit\Util\Annotation\DocBlock */ final class RegistryTest extends TestCase { public function testRegistryLookupWithExistingClassAnnotation(): void { $annotation = Registry::getInstance()->forClassName(self::class); self::assertSame( [ 'small' => [''], 'covers' => ['\PHPUnit\Util\Annotation\Registry'], 'uses' => ['\PHPUnit\Util\Annotation\DocBlock'], ], $annotation->symbolAnnotations() ); self::assertSame( $annotation, Registry::getInstance()->forClassName(self::class), 'Registry memoizes retrieved DocBlock instances' ); } public function testRegistryLookupWithExistingMethodAnnotation(): void { $annotation = Registry::getInstance()->forMethod( \NumericGroupAnnotationTest::class, 'testTicketAnnotationSupportsNumericValue' ); self::assertSame( [ 'testdox' => ['Empty test for @ticket numeric annotation values'], 'ticket' => ['3502'], 'see' => ['https://github.com/sebastianbergmann/phpunit/issues/3502'], ], $annotation->symbolAnnotations() ); self::assertSame( $annotation, Registry::getInstance()->forMethod( \NumericGroupAnnotationTest::class, 'testTicketAnnotationSupportsNumericValue' ), 'Registry memoizes retrieved DocBlock instances' ); } public function testClassLookupForAClassThatDoesNotExistFails(): void { $registry = Registry::getInstance(); $this->expectException(Exception::class); $registry->forClassName(\ThisClassDoesNotExist::class); } public function testMethodLookupForAMethodThatDoesNotExistFails(): void { $registry = Registry::getInstance(); $this->expectException(Exception::class); $registry->forMethod(self::class, 'thisMethodDoesNotExist'); } } PK!2kq q (Util/XDebugFilterScriptGeneratorTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util; use PHPUnit\Framework\TestCase; /** * @small * @covers \PHPUnit\Util\XdebugFilterScriptGenerator */ final class XDebugFilterScriptGeneratorTest extends TestCase { public function testReturnsExpectedScript(): void { $expectedDirectory = \sprintf('%s/', __DIR__); $expected = <<assertDirectoryNotExists($directoryPathThatDoesNotExist); $filterConfiguration = [ 'include' => [ 'directory' => [ [ 'path' => __DIR__, 'suffix' => '.php', 'prefix' => '', ], [ 'path' => \sprintf('%s/', __DIR__), 'suffix' => '.php', 'prefix' => '', ], [ 'path' => \sprintf('%s/./%s', \dirname(__DIR__), \basename(__DIR__)), 'suffix' => '.php', 'prefix' => '', ], [ 'path' => $directoryPathThatDoesNotExist, 'suffix' => '.php', 'prefix' => '', ], ], 'file' => [ 'src/foo.php', 'src/bar.php', ], ], 'exclude' => [ 'directory' => [], 'file' => [], ], ]; $writer = new XdebugFilterScriptGenerator; $actual = $writer->generate($filterConfiguration); $this->assertSame($expected, $actual); } } PK!bbUtil/GlobalStateTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util; use PHPUnit\Framework\TestCase; /** * @small */ final class GlobalStateTest extends TestCase { public function testIncludedFilesAsStringSkipsVfsProtocols(): void { $dir = __DIR__; $files = [ 'phpunit', // The 0 index is not used $dir . '/ConfigurationTest.php', $dir . '/GlobalStateTest.php', 'vfs://' . $dir . '/RegexTest.php', 'phpvfs53e46260465c7://' . $dir . '/TestClassTest.php', 'file://' . $dir . '/XmlTest.php', ]; $this->assertEquals( "require_once '" . $dir . "/ConfigurationTest.php';\n" . "require_once '" . $dir . "/GlobalStateTest.php';\n" . "require_once 'file://" . $dir . "/XmlTest.php';\n", GlobalState::processIncludedFilesAsString($files) ); } } PK!MrUtil/ColorTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util; use PHPUnit\Framework\TestCase; /** * @testdox Basic ANSI color highlighting support * @small */ final class ColorTest extends TestCase { /** * @testdox Colorize with $_dataName * @dataProvider colorizeProvider */ public function testColorize(string $color, string $buffer, string $expected): void { $this->assertSame($expected, Color::colorize($color, $buffer)); } /** * @testdox Colorize path $path after $prevPath * @dataProvider colorizePathProvider */ public function testColorizePath(?string $prevPath, string $path, bool $colorizeFilename, string $expected): void { $this->assertSame($expected, Color::colorizePath($path, $prevPath, $colorizeFilename)); } /** * @testdox dim($m) and colorize('dim',$m) return different ANSI codes */ public function testDimAndColorizeDimAreDifferent(): void { $buffer = 'some string'; $this->assertNotSame(Color::dim($buffer), Color::colorize('dim', $buffer)); } /** * @testdox Visualize all whitespace characters in $actual * @dataProvider whitespacedStringProvider */ public function testVisibleWhitespace(string $actual, string $expected): void { $this->assertSame($expected, Color::visualizeWhitespace($actual, true)); } /** * @testdox Visualize whitespace but ignore EOL */ public function testVisibleWhitespaceWithoutEOL(): void { $string = "line1\nline2\n"; $this->assertSame($string, Color::visualizeWhitespace($string, false)); } /** * @dataProvider unnamedDataSetProvider */ public function testPrettifyUnnamedDataprovider(int $value): void { $this->assertSame($value, $value); } /** * @dataProvider namedDataSetProvider */ public function testPrettifyNamedDataprovider(int $value): void { $this->assertSame($value, $value); } /** * @testdox TestDox shows name of data set $_dataName with value $value * @dataProvider namedDataSetProvider */ public function testTestdoxDatanameAsParameter(int $value): void { $this->assertSame($value, $value); } public function colorizeProvider(): array { return [ 'no color' => ['', 'string', 'string'], 'one color' => ['fg-blue', 'string', "\x1b[34mstring\x1b[0m"], 'multiple colors' => ['bold,dim,fg-blue,bg-yellow', 'string', "\x1b[1;2;34;43mstring\x1b[0m"], 'invalid color' => ['fg-invalid', 'some text', 'some text'], 'valid and invalid colors' => ['fg-invalid,bg-blue', 'some text', "\e[44msome text\e[0m"], ]; } public function colorizePathProvider(): array { $sep = \DIRECTORY_SEPARATOR; $sepDim = Color::dim($sep); return [ 'null previous path' => [ null, $sep . 'php' . $sep . 'unit' . $sep . 'test.phpt', false, $sepDim . 'php' . $sepDim . 'unit' . $sepDim . 'test.phpt', ], 'empty previous path' => [ '', $sep . 'php' . $sep . 'unit' . $sep . 'test.phpt', false, $sepDim . 'php' . $sepDim . 'unit' . $sepDim . 'test.phpt', ], 'from root' => [ $sep, $sep . 'php' . $sep . 'unit' . $sep . 'test.phpt', false, $sepDim . 'php' . $sepDim . 'unit' . $sepDim . 'test.phpt', ], 'partial part' => [ $sep . 'php' . $sep, $sep . 'php' . $sep . 'unit' . $sep . 'test.phpt', false, Color::dim($sep . 'php' . $sep) . 'unit' . $sepDim . 'test.phpt', ], 'colorize filename' => [ '', $sep . '_d-i.r' . $sep . 't-e_s.t.phpt', true, $sepDim . '_d-i.r' . $sepDim . 't' . Color::dim('-') . 'e' . Color::dim('_') . 's' . Color::dim('.') . 't' . Color::dim('.phpt'), ], ]; } public function whitespacedStringProvider(): array { return [ ['no-spaces', 'no-spaces', ], [ ' space invaders ', "\e[2m·\e[22mspace\e[2m···\e[22minvaders\e[2m·\e[22m", ], [ "\tindent, space and \\n\n\\r\r", "\e[2m⇥\e[22mindent,\e[2m·\e[22mspace\e[2m·\e[22mand\e[2m·\e[22m\\n\e[2m↵\e[22m\\r\e[2m⟵\e[22m", ], ]; } public function unnamedDataSetProvider(): array { return [ [1], [2], ]; } public function namedDataSetProvider(): array { return [ 'one' => [1], 'two' => [2], ]; } } PK!͏==#Util/ConfigurationGeneratorTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util; use PHPUnit\Framework\TestCase; /** * @small * @covers \PHPUnit\Util\ConfigurationGenerator */ final class ConfigurationGeneratorTest extends TestCase { public function testGeneratesConfigurationCorrectly(): void { $generator = new ConfigurationGenerator; $this->assertEquals( ' tests src ', $generator->generateDefaultConfiguration( 'X.Y.Z', 'vendor/autoload.php', 'tests', 'src' ) ); } } PK!#hhUtil/GetoptTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util; use PHPUnit\Framework\Exception; use PHPUnit\Framework\TestCase; /** * @small */ final class GetoptTest extends TestCase { public function testItIncludeTheLongOptionsAfterTheArgument(): void { $args = [ 'command', 'myArgument', '--colors', ]; $actual = Getopt::getopt($args, '', ['colors==']); $expected = [ [ [ '--colors', null, ], ], [ 'myArgument', ], ]; $this->assertEquals($expected, $actual); } public function testItIncludeTheShortOptionsAfterTheArgument(): void { $args = [ 'command', 'myArgument', '-v', ]; $actual = Getopt::getopt($args, 'v'); $expected = [ [ [ 'v', null, ], ], [ 'myArgument', ], ]; $this->assertEquals($expected, $actual); } public function testShortOptionUnrecognizedException(): void { $args = [ 'command', 'myArgument', '-v', ]; $this->expectException(Exception::class); $this->expectExceptionMessage('unrecognized option -- v'); Getopt::getopt($args, ''); } public function testShortOptionRequiresAnArgumentException(): void { $args = [ 'command', 'myArgument', '-f', ]; $this->expectException(Exception::class); $this->expectExceptionMessage('option requires an argument -- f'); Getopt::getopt($args, 'f:'); } public function testShortOptionHandleAnOptionalValue(): void { $args = [ 'command', 'myArgument', '-f', ]; $actual = Getopt::getopt($args, 'f::'); $expected = [ [ [ 'f', null, ], ], [ 'myArgument', ], ]; $this->assertEquals($expected, $actual); } public function testLongOptionIsAmbiguousException(): void { $args = [ 'command', '--col', ]; $this->expectException(Exception::class); $this->expectExceptionMessage('option --col is ambiguous'); Getopt::getopt($args, '', ['columns', 'colors']); } public function testLongOptionUnrecognizedException(): void { // the exception 'unrecognized option --option' is not thrown // if the there are not defined extended options $args = [ 'command', '--foo', ]; $this->expectException(Exception::class); $this->expectExceptionMessage('unrecognized option --foo'); Getopt::getopt($args, '', ['colors']); } public function testLongOptionRequiresAnArgumentException(): void { $args = [ 'command', '--foo', ]; $this->expectException(Exception::class); $this->expectExceptionMessage('option --foo requires an argument'); Getopt::getopt($args, '', ['foo=']); } public function testLongOptionDoesNotAllowAnArgumentException(): void { $args = [ 'command', '--foo=bar', ]; $this->expectException(Exception::class); $this->expectExceptionMessage("option --foo doesn't allow an argument"); Getopt::getopt($args, '', ['foo']); } public function testItHandlesLongParametesWithValues(): void { $command = 'command parameter-0 --exec parameter-1 --conf config.xml --optn parameter-2 --optn=content-of-o parameter-n'; $args = \explode(' ', $command); unset($args[0]); $expected = [ [ ['--exec', null], ['--conf', 'config.xml'], ['--optn', null], ['--optn', 'content-of-o'], ], [ 'parameter-0', 'parameter-1', 'parameter-2', 'parameter-n', ], ]; $actual = Getopt::getopt($args, '', ['exec', 'conf=', 'optn==']); $this->assertEquals($expected, $actual); } public function testItHandlesShortParametesWithValues(): void { $command = 'command parameter-0 -x parameter-1 -c config.xml -o parameter-2 -ocontent-of-o parameter-n'; $args = \explode(' ', $command); unset($args[0]); $expected = [ [ ['x', null], ['c', 'config.xml'], ['o', null], ['o', 'content-of-o'], ], [ 'parameter-0', 'parameter-1', 'parameter-2', 'parameter-n', ], ]; $actual = Getopt::getopt($args, 'xc:o::'); $this->assertEquals($expected, $actual); } } PK!úPggUtil/ConfigurationTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util; use PHPUnit\Framework\Exception; use PHPUnit\Framework\TestCase; use PHPUnit\Runner\TestSuiteSorter; use PHPUnit\TextUI\ResultPrinter; use PHPUnit\Util\TestDox\CliTestDoxPrinter; /** * @small */ final class ConfigurationTest extends TestCase { /** * @var Configuration */ protected $configuration; protected function setUp(): void { $this->configuration = Configuration::getInstance( TEST_FILES_PATH . 'configuration.xml' ); } public function testExceptionIsThrownForNotExistingConfigurationFile(): void { $this->expectException(Exception::class); Configuration::getInstance('not_existing_file.xml'); } public function testShouldReadColorsWhenTrueInConfigurationFile(): void { $configurationFilename = TEST_FILES_PATH . 'configuration.colors.true.xml'; $configurationInstance = Configuration::getInstance($configurationFilename); $configurationValues = $configurationInstance->getPHPUnitConfiguration(); $this->assertEquals(ResultPrinter::COLOR_AUTO, $configurationValues['colors']); } public function testShouldReadColorsWhenFalseInConfigurationFile(): void { $configurationFilename = TEST_FILES_PATH . 'configuration.colors.false.xml'; $configurationInstance = Configuration::getInstance($configurationFilename); $configurationValues = $configurationInstance->getPHPUnitConfiguration(); $this->assertEquals(ResultPrinter::COLOR_NEVER, $configurationValues['colors']); } public function testShouldReadColorsWhenEmptyInConfigurationFile(): void { $configurationFilename = TEST_FILES_PATH . 'configuration.colors.empty.xml'; $configurationInstance = Configuration::getInstance($configurationFilename); $configurationValues = $configurationInstance->getPHPUnitConfiguration(); $this->assertEquals(ResultPrinter::COLOR_NEVER, $configurationValues['colors']); } public function testShouldReadColorsWhenInvalidInConfigurationFile(): void { $configurationFilename = TEST_FILES_PATH . 'configuration.colors.invalid.xml'; $configurationInstance = Configuration::getInstance($configurationFilename); $configurationValues = $configurationInstance->getPHPUnitConfiguration(); $this->assertEquals(ResultPrinter::COLOR_NEVER, $configurationValues['colors']); } public function testInvalidConfigurationGeneratesValidationErrors(): void { $configurationFilename = TEST_FILES_PATH . 'configuration.colors.invalid.xml'; $configurationInstance = Configuration::getInstance($configurationFilename); $this->assertTrue($configurationInstance->hasValidationErrors()); } public function testShouldUseDefaultValuesForInvalidIntegers(): void { $configurationFilename = TEST_FILES_PATH . 'configuration.columns.default.xml'; $configurationInstance = Configuration::getInstance($configurationFilename); $configurationValues = $configurationInstance->getPHPUnitConfiguration(); $this->assertEquals(80, $configurationValues['columns']); } /** * @testdox Parse XML configuration root attribute $optionName = $optionValue * @dataProvider configurationRootOptionsProvider * * @group test-reorder * * @param bool|int|string $expected */ public function testShouldParseXmlConfigurationRootAttributes(string $optionName, string $optionValue, $expected): void { $tmpFilename = \sys_get_temp_dir() . \DIRECTORY_SEPARATOR . 'phpunit.' . $optionName . \uniqid() . '.xml'; $xml = "" . \PHP_EOL; \file_put_contents($tmpFilename, $xml); $configurationInstance = Configuration::getInstance($tmpFilename); $this->assertFalse($configurationInstance->hasValidationErrors(), 'option causes validation error'); $configurationValues = $configurationInstance->getPHPUnitConfiguration(); $this->assertEquals($expected, $configurationValues[$optionName]); @\unlink($tmpFilename); } public function configurationRootOptionsProvider(): array { return [ 'executionOrder default' => ['executionOrder', 'default', TestSuiteSorter::ORDER_DEFAULT], 'executionOrder random' => ['executionOrder', 'random', TestSuiteSorter::ORDER_RANDOMIZED], 'executionOrder reverse' => ['executionOrder', 'reverse', TestSuiteSorter::ORDER_REVERSED], 'executionOrder size' => ['executionOrder', 'size', TestSuiteSorter::ORDER_SIZE], 'cacheResult=false' => ['cacheResult', 'false', false], 'cacheResult=true' => ['cacheResult', 'true', true], 'cacheResultFile absolute path' => ['cacheResultFile', '/path/to/result/cache', '/path/to/result/cache'], 'columns' => ['columns', 'max', 'max'], 'stopOnFailure' => ['stopOnFailure', 'true', true], 'stopOnWarning' => ['stopOnWarning', 'true', true], 'stopOnIncomplete' => ['stopOnIncomplete', 'true', true], 'stopOnRisky' => ['stopOnRisky', 'true', true], 'stopOnSkipped' => ['stopOnSkipped', 'true', true], 'failOnWarning' => ['failOnWarning', 'true', true], 'failOnRisky' => ['failOnRisky', 'true', true], 'disableCodeCoverageIgnore' => ['disableCodeCoverageIgnore', 'true', true], 'processIsolation' => ['processIsolation', 'true', true], 'testSuiteLoaderFile absolute path' => ['testSuiteLoaderFile', '/path/to/file', '/path/to/file'], 'reverseDefectList' => ['reverseDefectList', 'true', true], 'registerMockObjectsFromTestArgumentsRecursively'=> ['registerMockObjectsFromTestArgumentsRecursively', 'true', true], ]; } public function testShouldParseXmlConfigurationExecutionOrderCombined(): void { $tmpFilename = \sys_get_temp_dir() . \DIRECTORY_SEPARATOR . 'phpunit.' . \uniqid() . '.xml'; $xml = "" . \PHP_EOL; \file_put_contents($tmpFilename, $xml); $configurationInstance = Configuration::getInstance($tmpFilename); $this->assertFalse($configurationInstance->hasValidationErrors(), 'option causes validation error'); $configurationValues = $configurationInstance->getPHPUnitConfiguration(); $this->assertSame(TestSuiteSorter::ORDER_DEFECTS_FIRST, $configurationValues['executionOrderDefects']); $this->assertSame(true, $configurationValues['resolveDependencies']); @\unlink($tmpFilename); } public function testFilterConfigurationIsReadCorrectly(): void { $this->assertEquals( [ 'whitelist' => [ 'addUncoveredFilesFromWhitelist' => true, 'processUncoveredFilesFromWhitelist' => false, 'include' => [ 'directory' => [ 0 => [ 'path' => '/path/to/files', 'prefix' => '', 'suffix' => '.php', 'group' => 'DEFAULT', ], ], 'file' => [ 0 => '/path/to/file', 1 => '/path/to/file', ], ], 'exclude' => [ 'directory' => [ 0 => [ 'path' => '/path/to/files', 'prefix' => '', 'suffix' => '.php', 'group' => 'DEFAULT', ], ], 'file' => [ 0 => '/path/to/file', ], ], ], ], $this->configuration->getFilterConfiguration() ); } public function testGroupConfigurationIsReadCorrectly(): void { $this->assertEquals( [ 'include' => [ 0 => 'name', ], 'exclude' => [ 0 => 'name', ], ], $this->configuration->getGroupConfiguration() ); } public function testTestdoxGroupConfigurationIsReadCorrectly(): void { $this->assertEquals( [ 'include' => [ 0 => 'name', ], 'exclude' => [ 0 => 'name', ], ], $this->configuration->getTestdoxGroupConfiguration() ); } public function testListenerConfigurationIsReadCorrectly(): void { $dir = __DIR__; $includePath = \ini_get('include_path'); \ini_set('include_path', $dir . \PATH_SEPARATOR . $includePath); $this->assertEquals( [ 0 => [ 'class' => 'MyListener', 'file' => '/optional/path/to/MyListener.php', 'arguments' => [ 0 => [ 0 => 'Sebastian', ], 1 => 22, 2 => 'April', 3 => 19.78, 4 => null, 5 => new \stdClass, 6 => TEST_FILES_PATH . 'MyTestFile.php', 7 => TEST_FILES_PATH . 'MyRelativePath', 8 => true, ], ], [ 'class' => 'IncludePathListener', 'file' => __FILE__, 'arguments' => [], ], [ 'class' => 'CompactArgumentsListener', 'file' => '/CompactArgumentsListener.php', 'arguments' => [ 0 => 42, 1 => false, ], ], ], $this->configuration->getListenerConfiguration() ); \ini_set('include_path', $includePath); } public function testExtensionConfigurationIsReadCorrectly(): void { $dir = __DIR__; $includePath = \ini_get('include_path'); \ini_set('include_path', $dir . \PATH_SEPARATOR . $includePath); $this->assertEquals( [ 0 => [ 'class' => 'MyExtension', 'file' => '/optional/path/to/MyExtension.php', 'arguments' => [ 0 => [ 0 => 'Sebastian', ], 1 => 22, 2 => 'April', 3 => 19.78, 4 => null, 5 => new \stdClass, 6 => TEST_FILES_PATH . 'MyTestFile.php', 7 => TEST_FILES_PATH . 'MyRelativePath', ], ], [ 'class' => 'IncludePathExtension', 'file' => __FILE__, 'arguments' => [], ], [ 'class' => 'CompactArgumentsExtension', 'file' => '/CompactArgumentsExtension.php', 'arguments' => [ 0 => 42, ], ], ], $this->configuration->getExtensionConfiguration() ); \ini_set('include_path', $includePath); } public function testLoggingConfigurationIsReadCorrectly(): void { $this->assertEquals( [ 'lowUpperBound' => '50', 'highLowerBound' => '90', 'coverage-html' => '/tmp/report', 'coverage-clover' => '/tmp/clover.xml', 'coverage-crap4j' => '/tmp/crap4j.xml', 'crap4jThreshold' => 50, 'coverage-text' => '/tmp/coverage.txt', 'coverageTextShowUncoveredFiles' => true, 'coverageTextShowOnlySummary' => true, 'json' => '/tmp/logfile.json', 'plain' => '/tmp/logfile.txt', 'tap' => '/tmp/logfile.tap', 'junit' => '/tmp/logfile.xml', 'testdox-html' => '/tmp/testdox.html', 'testdox-text' => '/tmp/testdox.txt', 'testdox-xml' => '/tmp/testdox.xml', ], $this->configuration->getLoggingConfiguration() ); } /** * @testdox PHP configuration is read correctly */ public function testPHPConfigurationIsReadCorrectly(): void { $this->assertEquals( [ 'include_path' => [ TEST_FILES_PATH . '.', '/path/to/lib', ], 'ini' => ['foo' => ['value' => 'bar'], 'highlight.keyword' => ['value' => '#123456'], 'highlight.string' => ['value' => 'TEST_FILES_PATH']], 'const' => ['FOO' => ['value' => false], 'BAR' => ['value' => true]], 'var' => ['foo' => ['value' => false]], 'env' => ['foo' => ['value' => true], 'bar' => ['value' => 'true', 'verbatim' => true], 'foo_force' => ['value' => 'forced', 'force' => true]], 'post' => ['foo' => ['value' => 'bar']], 'get' => ['foo' => ['value' => 'bar']], 'cookie' => ['foo' => ['value' => 'bar']], 'server' => ['foo' => ['value' => 'bar']], 'files' => ['foo' => ['value' => 'bar']], 'request'=> ['foo' => ['value' => 'bar']], ], $this->configuration->getPHPConfiguration() ); } /** * @testdox PHP configuration is handled correctly * @backupGlobals enabled */ public function testPHPConfigurationIsHandledCorrectly(): void { $savedIniHighlightKeyword = \ini_get('highlight.keyword'); $savedIniHighlightString = \ini_get('highlight.string'); $this->configuration->handlePHPConfiguration(); $path = TEST_FILES_PATH . '.' . \PATH_SEPARATOR . '/path/to/lib'; $this->assertStringStartsWith($path, \ini_get('include_path')); $this->assertEquals('#123456', \ini_get('highlight.keyword')); $this->assertEquals(TEST_FILES_PATH, \ini_get('highlight.string')); $this->assertFalse(\FOO); $this->assertTrue(\BAR); $this->assertFalse($GLOBALS['foo']); $this->assertTrue((bool) $_ENV['foo']); $this->assertEquals(1, \getenv('foo')); $this->assertEquals('bar', $_POST['foo']); $this->assertEquals('bar', $_GET['foo']); $this->assertEquals('bar', $_COOKIE['foo']); $this->assertEquals('bar', $_SERVER['foo']); $this->assertEquals('bar', $_FILES['foo']); $this->assertEquals('bar', $_REQUEST['foo']); \ini_set('highlight.keyword', $savedIniHighlightKeyword); \ini_set('highlight.string', $savedIniHighlightString); } /** * @testdox handlePHPConfiguration() does not overwrite existing $ENV[] variables * @backupGlobals enabled * * @see https://github.com/sebastianbergmann/phpunit/issues/1181 */ public function testHandlePHPConfigurationDoesNotOverwriteExistingEnvArrayVariables(): void { $_ENV['foo'] = false; $this->configuration->handlePHPConfiguration(); $this->assertFalse($_ENV['foo']); $this->assertEquals('forced', \getenv('foo_force')); } /** * @testdox handlePHPConfiguration() does force overwritten existing $ENV[] variables * @backupGlobals enabled * * @see https://github.com/sebastianbergmann/phpunit/issues/2353 */ public function testHandlePHPConfigurationDoesForceOverwrittenExistingEnvArrayVariables(): void { $_ENV['foo_force'] = false; $this->configuration->handlePHPConfiguration(); $this->assertEquals('forced', $_ENV['foo_force']); $this->assertEquals('forced', \getenv('foo_force')); } /** * @testdox handlePHPConfiguration() does not overwrite variables from putenv() * @backupGlobals enabled * * @see https://github.com/sebastianbergmann/phpunit/issues/1181 */ public function testHandlePHPConfigurationDoesNotOverwriteVariablesFromPutEnv(): void { $backupFoo = \getenv('foo'); \putenv('foo=putenv'); $this->configuration->handlePHPConfiguration(); $this->assertEquals('putenv', $_ENV['foo']); $this->assertEquals('putenv', \getenv('foo')); if ($backupFoo === false) { \putenv('foo'); // delete variable from environment } else { \putenv("foo=$backupFoo"); } } /** * @testdox handlePHPConfiguration() does overwrite variables from putenv() when forced * @backupGlobals enabled * * @see https://github.com/sebastianbergmann/phpunit/issues/1181 */ public function testHandlePHPConfigurationDoesOverwriteVariablesFromPutEnvWhenForced(): void { \putenv('foo_force=putenv'); $this->configuration->handlePHPConfiguration(); $this->assertEquals('forced', $_ENV['foo_force']); $this->assertEquals('forced', \getenv('foo_force')); } /** * @testdox PHPUnit configuration is read correctly */ public function testPHPUnitConfigurationIsReadCorrectly(): void { $this->assertEquals( [ 'backupGlobals' => true, 'backupStaticAttributes' => false, 'beStrictAboutChangesToGlobalState' => false, 'bootstrap' => '/path/to/bootstrap.php', 'cacheTokens' => false, 'columns' => 80, 'colors' => 'never', 'stderr' => false, 'convertDeprecationsToExceptions' => true, 'convertErrorsToExceptions' => true, 'convertNoticesToExceptions' => true, 'convertWarningsToExceptions' => true, 'forceCoversAnnotation' => false, 'stopOnFailure' => false, 'stopOnWarning' => false, 'reportUselessTests' => false, 'strictCoverage' => false, 'disallowTestOutput' => false, 'defaultTimeLimit' => 123, 'enforceTimeLimit' => false, 'extensionsDirectory' => '/tmp', 'printerClass' => 'PHPUnit\TextUI\ResultPrinter', 'testSuiteLoaderClass' => 'PHPUnit\Runner\StandardTestSuiteLoader', 'defaultTestSuite' => 'My Test Suite', 'verbose' => false, 'timeoutForSmallTests' => 1, 'timeoutForMediumTests' => 10, 'timeoutForLargeTests' => 60, 'beStrictAboutResourceUsageDuringSmallTests' => false, 'disallowTodoAnnotatedTests' => false, 'failOnWarning' => false, 'failOnRisky' => false, 'ignoreDeprecatedCodeUnitsFromCodeCoverage' => false, 'executionOrder' => TestSuiteSorter::ORDER_DEFAULT, 'executionOrderDefects' => TestSuiteSorter::ORDER_DEFAULT, 'resolveDependencies' => false, 'noInteraction' => true, ], $this->configuration->getPHPUnitConfiguration() ); } public function testXincludeInConfiguration(): void { $configurationWithXinclude = Configuration::getInstance( TEST_FILES_PATH . 'configuration_xinclude.xml' ); $this->assertConfigurationEquals( $this->configuration, $configurationWithXinclude ); } /** * @ticket 1311 */ public function testWithEmptyConfigurations(): void { $emptyConfiguration = Configuration::getInstance( TEST_FILES_PATH . 'configuration_empty.xml' ); $logging = $emptyConfiguration->getLoggingConfiguration(); $this->assertEmpty($logging); $php = $emptyConfiguration->getPHPConfiguration(); $this->assertEmpty($php['include_path']); $phpunit = $emptyConfiguration->getPHPUnitConfiguration(); $this->assertArrayNotHasKey('bootstrap', $phpunit); $this->assertArrayNotHasKey('testSuiteLoaderFile', $phpunit); $this->assertArrayNotHasKey('printerFile', $phpunit); $suite = $emptyConfiguration->getTestSuiteConfiguration(); $this->assertEmpty($suite->getGroups()); $filter = $emptyConfiguration->getFilterConfiguration(); $this->assertEmpty($filter['whitelist']['include']['directory']); $this->assertEmpty($filter['whitelist']['include']['file']); $this->assertEmpty($filter['whitelist']['exclude']['directory']); $this->assertEmpty($filter['whitelist']['exclude']['file']); } public function testGetTestSuiteNamesReturnsTheNamesIfDefined(): void { $configuration = Configuration::getInstance( TEST_FILES_PATH . 'configuration.suites.xml' ); $names = $configuration->getTestSuiteNames(); $this->assertEquals(['Suite One', 'Suite Two'], $names); } public function testTestSuiteConfigurationForASingleFileInASuite(): void { $configuration = Configuration::getInstance( TEST_FILES_PATH . 'configuration.one-file-suite.xml' ); $config = $configuration->getTestSuiteConfiguration(); $tests = $config->tests(); $this->assertCount(1, $tests); } public function test_TestDox_configuration_is_parsed_correctly(): void { $configuration = Configuration::getInstance( TEST_FILES_PATH . 'configuration_testdox.xml' ); $config = $configuration->getPHPUnitConfiguration(); $this->assertSame(CliTestDoxPrinter::class, $config['printerClass']); } public function test_Conflict_between_testdox_and_printerClass_is_detected(): void { $configuration = Configuration::getInstance( TEST_FILES_PATH . 'configuration_testdox_printerClass.xml' ); $config = $configuration->getPHPUnitConfiguration(); $this->assertSame('foo', $config['printerClass']); $this->assertTrue($config['conflictBetweenPrinterClassAndTestdox']); } /** * Asserts that the values in $actualConfiguration equal $expectedConfiguration. * * @throws Exception * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ protected function assertConfigurationEquals(Configuration $expectedConfiguration, Configuration $actualConfiguration): void { $this->assertEquals( $expectedConfiguration->getFilterConfiguration(), $actualConfiguration->getFilterConfiguration() ); $this->assertEquals( $expectedConfiguration->getGroupConfiguration(), $actualConfiguration->getGroupConfiguration() ); $this->assertEquals( $expectedConfiguration->getListenerConfiguration(), $actualConfiguration->getListenerConfiguration() ); $this->assertEquals( $expectedConfiguration->getLoggingConfiguration(), $actualConfiguration->getLoggingConfiguration() ); $this->assertEquals( $expectedConfiguration->getPHPConfiguration(), $actualConfiguration->getPHPConfiguration() ); $this->assertEquals( $expectedConfiguration->getPHPUnitConfiguration(), $actualConfiguration->getPHPUnitConfiguration() ); $this->assertEquals( $expectedConfiguration->getTestSuiteConfiguration()->tests(), $actualConfiguration->getTestSuiteConfiguration()->tests() ); } } PK!OffUtil/XmlTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util; use PHPUnit\Framework\Exception; use PHPUnit\Framework\TestCase; /** * @small */ final class XmlTest extends TestCase { /** * @dataProvider charProvider */ public function testPrepareString(string $char): void { $e = null; $escapedString = Xml::prepareString($char); $xml = "$escapedString"; $dom = new \DOMDocument('1.0', 'UTF-8'); try { $dom->loadXML($xml); } catch (Exception $e) { } $this->assertNull( $e, \sprintf( '\PHPUnit\Util\Xml::prepareString("\x%02x") should not crash DomDocument', \ord($char) ) ); } public function charProvider(): array { $data = []; for ($i = 0; $i < 256; $i++) { $data[] = [\chr($i)]; } return $data; } public function testLoadEmptyString(): void { $this->expectException(Exception::class); $this->expectExceptionMessage('Could not load XML from empty string'); Xml::load(''); } public function testLoadArray(): void { $this->expectException(Exception::class); $this->expectExceptionMessage('Could not load XML from array'); Xml::load([1, 2, 3]); } public function testLoadBoolean(): void { $this->expectException(Exception::class); $this->expectExceptionMessage('Could not load XML from boolean'); Xml::load(false); } /** * @testdox Nested xmlToVariable() */ public function testNestedXmlToVariable(): void { $xml = 'foobar'; $dom = new \DOMDocument; $dom->loadXML($xml); $expected = [ 'a' => [ 'b' => 'foo', ], 'c' => 'bar', ]; $actual = Xml::xmlToVariable($dom->documentElement); $this->assertSame($expected, $actual); } /** * @testdox xmlToVariable() can handle multiple of the same argument type */ public function testXmlToVariableCanHandleMultipleOfTheSameArgumentType(): void { $xml = 'abc'; $dom = new \DOMDocument; $dom->loadXML($xml); $expected = ['a' => 'a', 'b' => 'b', 'c' => 'c']; $actual = Xml::xmlToVariable($dom->documentElement); $this->assertSame($expected, (array) $actual); } /** * @testdox xmlToVariable() can construct objects with constructor arguments recursively */ public function testXmlToVariableCanConstructObjectsWithConstructorArgumentsRecursively(): void { $xml = 'one0two'; $dom = new \DOMDocument; $dom->loadXML($xml); $actual = Xml::xmlToVariable($dom->documentElement); $this->assertEquals('one', $actual->getMessage()); $this->assertEquals('two', $actual->getPrevious()->getMessage()); } } PK!ƴ  Util/JsonTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util; use PHPUnit\Framework\Exception; use PHPUnit\Framework\TestCase; /** * @small */ final class JsonTest extends TestCase { /** * @testdox Canonicalize $actual * @dataProvider canonicalizeProvider * * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testCanonicalize($actual, $expected, $expectError): void { [$error, $canonicalized] = Json::canonicalize($actual); $this->assertEquals($expectError, $error); if (!$expectError) { $this->assertEquals($expected, $canonicalized); } } public function canonicalizeProvider(): array { return [ ['{"name":"John","age":"35"}', '{"age":"35","name":"John"}', false], ['{"name":"John","age":"35","kids":[{"name":"Petr","age":"5"}]}', '{"age":"35","kids":[{"age":"5","name":"Petr"}],"name":"John"}', false], ['"name":"John","age":"35"}', '{"age":"35","name":"John"}', true], ]; } /** * @testdox Prettify $actual to $expected * @dataProvider prettifyProvider * * @throws \PHPUnit\Framework\Exception * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testPrettify($actual, $expected): void { $this->assertEquals($expected, Json::prettify($actual)); } public function prettifyProvider(): array { return [ ['{"name":"John","age": "5"}', "{\n \"name\": \"John\",\n \"age\": \"5\"\n}"], ['{"url":"https://www.example.com/"}', "{\n \"url\": \"https://www.example.com/\"\n}"], ['"Кириллица and 中文"', '"Кириллица and 中文"'], ]; } /** * @dataProvider prettifyExceptionProvider */ public function testPrettifyException($json): void { $this->expectException(Exception::class); $this->expectExceptionMessage('Cannot prettify invalid json'); Json::prettify($json); } public function prettifyExceptionProvider(): array { return [ ['"name":"John","age": "5"}'], [''], ]; } } PK!ZGA``Util/RegularExpressionTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util; use PHPUnit\Framework\TestCase; /** * @small */ final class RegularExpressionTest extends TestCase { public function validRegexpProvider(): array { return [ ['#valid regexp#', 'valid regexp', 1], [';val.*xp;', 'valid regexp', 1], ['/val.*xp/i', 'VALID REGEXP', 1], ['/a val.*p/', 'valid regexp', 0], ]; } public function invalidRegexpProvider(): array { return [ ['valid regexp', 'valid regexp'], [';val.*xp', 'valid regexp'], ['val.*xp/i', 'VALID REGEXP'], ]; } /** * @testdox Valid regex $pattern on $subject returns $return * @dataProvider validRegexpProvider * * @throws \Exception * @throws \PHPUnit\Framework\ExpectationFailedException */ public function testValidRegex($pattern, $subject, $return): void { $this->assertEquals($return, RegularExpression::safeMatch($pattern, $subject)); } /** * @testdox Invalid regex $pattern on $subject * @dataProvider invalidRegexpProvider * * @throws \Exception * @throws \PHPUnit\Framework\ExpectationFailedException */ public function testInvalidRegex($pattern, $subject): void { $this->assertFalse(RegularExpression::safeMatch($pattern, $subject)); } } PK!/Util/TestClassTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util; use PharIo\Version\VersionConstraint; use PHPUnit\Framework\CodeCoverageException; use PHPUnit\Framework\InvalidDataProviderException; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\Warning; use PHPUnit\Util\Annotation\DocBlock; /** * @small */ final class TestClassTest extends TestCase { /** * @var string */ private $fileRequirementsTest; /** * @testdox Test::getRequirements() for $test * @dataProvider requirementsProvider * * @throws Warning * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testGetRequirements($test, $result): void { $this->assertEquals( $result, Test::getRequirements(\RequirementsTest::class, $test) ); } public function requirementsProvider(): array { return [ [ 'testOne', ['__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), ]], ], [ 'testTwo', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHPUnit' => 19, ], 'PHPUnit' => ['version' => '1.0', 'operator' => ''], ], ], [ 'testThree', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 26, ], 'PHP' => ['version' => '2.0', 'operator' => ''], ], ], [ 'testFour', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHPUnit' => 33, 'PHP' => 34, ], 'PHPUnit' => ['version' => '2.0', 'operator' => ''], 'PHP' => ['version' => '1.0', 'operator' => ''], ], ], [ 'testFive', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 41, ], 'PHP' => ['version' => '5.4.0RC6', 'operator' => ''], ], ], [ 'testSix', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 48, ], 'PHP' => ['version' => '5.4.0-alpha1', 'operator' => ''], ], ], [ 'testSeven', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 55, ], 'PHP' => ['version' => '5.4.0beta2', 'operator' => ''], ], ], [ 'testEight', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 62, ], 'PHP' => ['version' => '5.4-dev', 'operator' => ''], ], ], [ 'testNine', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'function_testFunc' => 69, ], 'functions' => ['testFunc'], ], ], [ 'testTen', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'extension_testExt' => 85, ], 'extensions' => ['testExt'], ], ], [ 'testEleven', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'OS' => 92, 'OSFAMILY' => 93, ], 'OS' => 'SunOS', 'OSFAMILY' => 'Solaris', ], ], [ 'testSpace', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'extension_spl' => 171, 'OS' => 172, ], 'extensions' => ['spl'], 'OS' => '.*', ], ], [ 'testAllPossibleRequirements', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 100, 'PHPUnit' => 101, 'OS' => 102, 'function_testFuncOne' => 103, 'function_testFunc2' => 104, 'extension_testExtOne' => 105, 'extension_testExt2' => 106, 'extension_testExtThree' => 107, '__SETTING_not_a_setting' => 108, ], 'PHP' => ['version' => '99-dev', 'operator' => ''], 'PHPUnit' => ['version' => '9-dev', 'operator' => ''], 'OS' => 'DOESNOTEXIST', 'functions' => [ 'testFuncOne', 'testFunc2', ], 'setting' => [ 'not_a_setting' => 'Off', ], 'extensions' => [ 'testExtOne', 'testExt2', 'testExtThree', ], 'extension_versions' => [ 'testExtThree' => ['version' => '2.0', 'operator' => ''], ], ], ], ['testSpecificExtensionVersion', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'extension_testExt' => 179, ], 'extension_versions' => ['testExt' => ['version' => '1.8.0', 'operator' => '']], 'extensions' => ['testExt'], ], ], ['testPHPVersionOperatorLessThan', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 187, ], 'PHP' => ['version' => '5.4', 'operator' => '<'], ], ], ['testPHPVersionOperatorLessThanEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 195, ], 'PHP' => ['version' => '5.4', 'operator' => '<='], ], ], ['testPHPVersionOperatorGreaterThan', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 203, ], 'PHP' => ['version' => '99', 'operator' => '>'], ], ], ['testPHPVersionOperatorGreaterThanEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 211, ], 'PHP' => ['version' => '99', 'operator' => '>='], ], ], ['testPHPVersionOperatorEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 219, ], 'PHP' => ['version' => '5.4', 'operator' => '='], ], ], ['testPHPVersionOperatorDoubleEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 227, ], 'PHP' => ['version' => '5.4', 'operator' => '=='], ], ], ['testPHPVersionOperatorBangEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 235, ], 'PHP' => ['version' => '99', 'operator' => '!='], ], ], ['testPHPVersionOperatorNotEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 243, ], 'PHP' => ['version' => '99', 'operator' => '<>'], ], ], ['testPHPVersionOperatorNoSpace', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHP' => 251, ], 'PHP' => ['version' => '99', 'operator' => '>='], ], ], ['testPHPUnitVersionOperatorLessThan', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHPUnit' => 259, ], 'PHPUnit' => ['version' => '1.0', 'operator' => '<'], ], ], ['testPHPUnitVersionOperatorLessThanEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHPUnit' => 267, ], 'PHPUnit' => ['version' => '1.0', 'operator' => '<='], ], ], ['testPHPUnitVersionOperatorGreaterThan', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHPUnit' => 275, ], 'PHPUnit' => ['version' => '99', 'operator' => '>'], ], ], ['testPHPUnitVersionOperatorGreaterThanEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHPUnit' => 283, ], 'PHPUnit' => ['version' => '99', 'operator' => '>='], ], ], ['testPHPUnitVersionOperatorEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHPUnit' => 291, ], 'PHPUnit' => ['version' => '1.0', 'operator' => '='], ], ], ['testPHPUnitVersionOperatorDoubleEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHPUnit' => 299, ], 'PHPUnit' => ['version' => '1.0', 'operator' => '=='], ], ], ['testPHPUnitVersionOperatorBangEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHPUnit' => 307, ], 'PHPUnit' => ['version' => '99', 'operator' => '!='], ], ], ['testPHPUnitVersionOperatorNotEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHPUnit' => 315, ], 'PHPUnit' => ['version' => '99', 'operator' => '<>'], ], ], ['testPHPUnitVersionOperatorNoSpace', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'PHPUnit' => 323, ], 'PHPUnit' => ['version' => '99', 'operator' => '>='], ], ], ['testExtensionVersionOperatorLessThanEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'extension_testExtOne' => 337, ], 'extensions' => ['testExtOne'], 'extension_versions' => ['testExtOne' => ['version' => '1.0', 'operator' => '<=']], ], ], ['testExtensionVersionOperatorGreaterThan', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'extension_testExtOne' => 344, ], 'extensions' => ['testExtOne'], 'extension_versions' => ['testExtOne' => ['version' => '99', 'operator' => '>']], ], ], ['testExtensionVersionOperatorGreaterThanEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'extension_testExtOne' => 351, ], 'extensions' => ['testExtOne'], 'extension_versions' => ['testExtOne' => ['version' => '99', 'operator' => '>=']], ], ], ['testExtensionVersionOperatorEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'extension_testExtOne' => 358, ], 'extensions' => ['testExtOne'], 'extension_versions' => ['testExtOne' => ['version' => '1.0', 'operator' => '=']], ], ], ['testExtensionVersionOperatorDoubleEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'extension_testExtOne' => 365, ], 'extensions' => ['testExtOne'], 'extension_versions' => ['testExtOne' => ['version' => '1.0', 'operator' => '==']], ], ], ['testExtensionVersionOperatorBangEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'extension_testExtOne' => 372, ], 'extensions' => ['testExtOne'], 'extension_versions' => ['testExtOne' => ['version' => '99', 'operator' => '!=']], ], ], ['testExtensionVersionOperatorNotEquals', [ '__OFFSET' => [ '__FILE' => $this->getRequirementsTestClassFile(), 'extension_testExtOne' => 379, ], 'extensions' => ['testExtOne'], 'extension_versions' => ['testExtOne' => ['version' => '99', 'operator' => '<>']], ], ], ['testExtensionVersionOperatorNoSpace', [ '__OFFSET' => [ '__FILE' => $this->fileRequirementsTest, 'extension_testExtOne' => 386, ], 'extensions' => ['testExtOne'], 'extension_versions' => ['testExtOne' => ['version' => '99', 'operator' => '>=']], ], ], ]; } /** * @testdox Test::getRequirements() with constraints for $test * @dataProvider requirementsWithVersionConstraintsProvider * * @throws Exception * @throws Warning * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testGetRequirementsWithVersionConstraints($test, array $result): void { $requirements = Test::getRequirements(\RequirementsTest::class, $test); foreach ($result as $type => $expected_requirement) { $this->assertArrayHasKey( "{$type}_constraint", $requirements ); $this->assertArrayHasKey( 'constraint', $requirements["{$type}_constraint"] ); $this->assertInstanceOf( VersionConstraint::class, $requirements["{$type}_constraint"]['constraint'] ); $this->assertSame( $expected_requirement['constraint'], $requirements["{$type}_constraint"]['constraint']->asString() ); } } public function requirementsWithVersionConstraintsProvider(): array { return [ [ 'testVersionConstraintTildeMajor', [ 'PHP' => [ 'constraint' => '~1.0', ], 'PHPUnit' => [ 'constraint' => '~2.0', ], ], ], [ 'testVersionConstraintCaretMajor', [ 'PHP' => [ 'constraint' => '^1.0', ], 'PHPUnit' => [ 'constraint' => '^2.0', ], ], ], [ 'testVersionConstraintTildeMinor', [ 'PHP' => [ 'constraint' => '~3.4.7', ], 'PHPUnit' => [ 'constraint' => '~4.7.1', ], ], ], [ 'testVersionConstraintCaretMinor', [ 'PHP' => [ 'constraint' => '^7.0.17', ], 'PHPUnit' => [ 'constraint' => '^4.7.1', ], ], ], [ 'testVersionConstraintCaretOr', [ 'PHP' => [ 'constraint' => '^5.6 || ^7.0', ], 'PHPUnit' => [ 'constraint' => '^5.0 || ^6.0', ], ], ], [ 'testVersionConstraintTildeOr', [ 'PHP' => [ 'constraint' => '~5.6.22 || ~7.0.17', ], 'PHPUnit' => [ 'constraint' => '^5.0.5 || ^6.0.6', ], ], ], [ 'testVersionConstraintTildeOrCaret', [ 'PHP' => [ 'constraint' => '~5.6.22 || ^7.0', ], 'PHPUnit' => [ 'constraint' => '~5.6.22 || ^7.0', ], ], ], [ 'testVersionConstraintCaretOrTilde', [ 'PHP' => [ 'constraint' => '^5.6 || ~7.0.17', ], 'PHPUnit' => [ 'constraint' => '^5.6 || ~7.0.17', ], ], ], [ 'testVersionConstraintRegexpIgnoresWhitespace', [ 'PHP' => [ 'constraint' => '~5.6.22 || ~7.0.17', ], 'PHPUnit' => [ 'constraint' => '~5.6.22 || ~7.0.17', ], ], ], ]; } /** * @dataProvider requirementsWithInvalidVersionConstraintsThrowsExceptionProvider * * @throws Warning */ public function testGetRequirementsWithInvalidVersionConstraintsThrowsException($test): void { $this->expectException(Warning::class); Test::getRequirements(\RequirementsTest::class, $test); } public function requirementsWithInvalidVersionConstraintsThrowsExceptionProvider(): array { return [ ['testVersionConstraintInvalidPhpConstraint'], ['testVersionConstraintInvalidPhpUnitConstraint'], ]; } public function testGetRequirementsMergesClassAndMethodDocBlocks(): void { $reflector = new \ReflectionClass(\RequirementsClassDocBlockTest::class); $file = $reflector->getFileName(); $expectedAnnotations = [ '__OFFSET' => [ '__FILE' => $file, 'PHP' => 21, 'PHPUnit' => 22, 'OS' => 23, 'function_testFuncClass' => 15, 'extension_testExtClass' => 16, 'function_testFuncMethod' => 24, 'extension_testExtMethod' => 25, ], 'PHP' => ['version' => '5.4', 'operator' => ''], 'PHPUnit' => ['version' => '3.7', 'operator' => ''], 'OS' => 'WINNT', 'functions' => [ 'testFuncClass', 'testFuncMethod', ], 'extensions' => [ 'testExtClass', 'testExtMethod', ], ]; $this->assertEquals( $expectedAnnotations, Test::getRequirements(\RequirementsClassDocBlockTest::class, 'testMethod') ); } /** * @testdox Test::getMissingRequirements() for $test * @dataProvider missingRequirementsProvider * * @throws Warning * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testGetMissingRequirements($test, $result): void { $this->assertEquals( $result, Test::getMissingRequirements(\RequirementsTest::class, $test) ); } public function missingRequirementsProvider(): array { return [ ['testOne', []], ['testNine', [ '__OFFSET_LINE=69', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'Function testFunc is required.', ]], ['testTen', [ '__OFFSET_LINE=85', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'Extension testExt is required.', ]], ['testAlwaysSkip', [ '__OFFSET_LINE=143', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHPUnit >= 1111111 is required.', ]], ['testAlwaysSkip2', [ '__OFFSET_LINE=150', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHP >= 9999999 is required.', ]], ['testAlwaysSkip3', [ '__OFFSET_LINE=157', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'Operating system matching /DOESNOTEXIST/i is required.', ]], ['testAllPossibleRequirements', [ '__OFFSET_LINE=100', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHP >= 99-dev is required.', 'PHPUnit >= 9-dev is required.', 'Operating system matching /DOESNOTEXIST/i is required.', 'Function testFuncOne is required.', 'Function testFunc2 is required.', 'Setting "not_a_setting" must be "Off".', 'Extension testExtOne is required.', 'Extension testExt2 is required.', 'Extension testExtThree >= 2.0 is required.', ]], ['testPHPVersionOperatorLessThan', [ '__OFFSET_LINE=187', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHP < 5.4 is required.', ]], ['testPHPVersionOperatorLessThanEquals', [ '__OFFSET_LINE=195', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHP <= 5.4 is required.', ]], ['testPHPVersionOperatorGreaterThan', [ '__OFFSET_LINE=203', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHP > 99 is required.', ]], ['testPHPVersionOperatorGreaterThanEquals', [ '__OFFSET_LINE=211', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHP >= 99 is required.', ]], ['testPHPVersionOperatorNoSpace', [ '__OFFSET_LINE=251', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHP >= 99 is required.', ]], ['testPHPVersionOperatorEquals', [ '__OFFSET_LINE=219', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHP = 5.4 is required.', ]], ['testPHPVersionOperatorDoubleEquals', [ '__OFFSET_LINE=227', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHP == 5.4 is required.', ]], ['testPHPUnitVersionOperatorLessThan', [ '__OFFSET_LINE=259', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHPUnit < 1.0 is required.', ]], ['testPHPUnitVersionOperatorLessThanEquals', [ '__OFFSET_LINE=267', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHPUnit <= 1.0 is required.', ]], ['testPHPUnitVersionOperatorGreaterThan', [ '__OFFSET_LINE=275', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHPUnit > 99 is required.', ]], ['testPHPUnitVersionOperatorGreaterThanEquals', [ '__OFFSET_LINE=283', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHPUnit >= 99 is required.', ]], ['testPHPUnitVersionOperatorEquals', [ '__OFFSET_LINE=291', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHPUnit = 1.0 is required.', ]], ['testPHPUnitVersionOperatorDoubleEquals', [ '__OFFSET_LINE=299', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHPUnit == 1.0 is required.', ]], ['testPHPUnitVersionOperatorNoSpace', [ '__OFFSET_LINE=323', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHPUnit >= 99 is required.', ]], ['testExtensionVersionOperatorLessThan', [ '__OFFSET_LINE=330', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'Extension testExtOne < 1.0 is required.', ]], ['testExtensionVersionOperatorLessThanEquals', [ '__OFFSET_LINE=337', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'Extension testExtOne <= 1.0 is required.', ]], ['testExtensionVersionOperatorGreaterThan', [ '__OFFSET_LINE=344', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'Extension testExtOne > 99 is required.', ]], ['testExtensionVersionOperatorGreaterThanEquals', [ '__OFFSET_LINE=351', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'Extension testExtOne >= 99 is required.', ]], ['testExtensionVersionOperatorEquals', [ '__OFFSET_LINE=358', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'Extension testExtOne = 1.0 is required.', ]], ['testExtensionVersionOperatorDoubleEquals', [ '__OFFSET_LINE=365', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'Extension testExtOne == 1.0 is required.', ]], ['testExtensionVersionOperatorNoSpace', [ '__OFFSET_LINE=386', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'Extension testExtOne >= 99 is required.', ]], ['testVersionConstraintTildeMajor', [ '__OFFSET_LINE=393', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHP version does not match the required constraint ~1.0.', 'PHPUnit version does not match the required constraint ~2.0.', ]], ['testVersionConstraintCaretMajor', [ '__OFFSET_LINE=401', '__OFFSET_FILE=' . $this->getRequirementsTestClassFile(), 'PHP version does not match the required constraint ^1.0.', 'PHPUnit version does not match the required constraint ^2.0.', ]], ]; } /** * @todo This test does not really test functionality of \PHPUnit\Util\Test */ public function testGetProvidedDataRegEx(): void { $result = \preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider method', $matches); $this->assertEquals(1, $result); $this->assertEquals('method', $matches[1]); $result = \preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider class::method', $matches); $this->assertEquals(1, $result); $this->assertEquals('class::method', $matches[1]); $result = \preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider namespace\class::method', $matches); $this->assertEquals(1, $result); $this->assertEquals('namespace\class::method', $matches[1]); $result = \preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider namespace\namespace\class::method', $matches); $this->assertEquals(1, $result); $this->assertEquals('namespace\namespace\class::method', $matches[1]); $result = \preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider メソッド', $matches); $this->assertEquals(1, $result); $this->assertEquals('メソッド', $matches[1]); } /** * Check if all data providers are being merged. */ public function testMultipleDataProviders(): void { $dataSets = Test::getProvidedData(\MultipleDataProviderTest::class, 'testOne'); $this->assertCount(9, $dataSets); $aCount = 0; $bCount = 0; $cCount = 0; for ($i = 0; $i < 9; $i++) { $aCount += $dataSets[$i][0] != null ? 1 : 0; $bCount += $dataSets[$i][1] != null ? 1 : 0; $cCount += $dataSets[$i][2] != null ? 1 : 0; } $this->assertEquals(3, $aCount); $this->assertEquals(3, $bCount); $this->assertEquals(3, $cCount); } public function testMultipleYieldIteratorDataProviders(): void { $dataSets = Test::getProvidedData(\MultipleDataProviderTest::class, 'testTwo'); $this->assertCount(9, $dataSets); $aCount = 0; $bCount = 0; $cCount = 0; for ($i = 0; $i < 9; $i++) { $aCount += $dataSets[$i][0] != null ? 1 : 0; $bCount += $dataSets[$i][1] != null ? 1 : 0; $cCount += $dataSets[$i][2] != null ? 1 : 0; } $this->assertEquals(3, $aCount); $this->assertEquals(3, $bCount); $this->assertEquals(3, $cCount); } public function testWithVariousIterableDataProvidersFromParent(): void { $dataSets = Test::getProvidedData(\VariousIterableDataProviderTest::class, 'testFromParent'); $this->assertEquals([ ['J'], ['K'], ['L'], ['M'], ['N'], ['O'], ['P'], ['Q'], ['R'], ], $dataSets); } public function testWithVariousIterableDataProvidersInParent(): void { $dataSets = Test::getProvidedData(\VariousIterableDataProviderTest::class, 'testInParent'); $this->assertEquals([ ['J'], ['K'], ['L'], ['M'], ['N'], ['O'], ['P'], ['Q'], ['R'], ], $dataSets); } public function testWithVariousIterableAbstractDataProviders(): void { $dataSets = Test::getProvidedData(\VariousIterableDataProviderTest::class, 'testAbstract'); $this->assertEquals([ ['S'], ['T'], ['U'], ['V'], ['W'], ['X'], ['Y'], ['Z'], ['P'], ], $dataSets); } public function testWithVariousIterableStaticDataProviders(): void { $dataSets = Test::getProvidedData(\VariousIterableDataProviderTest::class, 'testStatic'); $this->assertEquals([ ['A'], ['B'], ['C'], ['D'], ['E'], ['F'], ['G'], ['H'], ['I'], ], $dataSets); } public function testWithVariousIterableNonStaticDataProviders(): void { $dataSets = Test::getProvidedData(\VariousIterableDataProviderTest::class, 'testNonStatic'); $this->assertEquals([ ['S'], ['T'], ['U'], ['V'], ['W'], ['X'], ['Y'], ['Z'], ['P'], ], $dataSets); } public function testWithDuplicateKeyDataProviders(): void { $this->expectException(InvalidDataProviderException::class); $this->expectExceptionMessage('The key "foo" has already been defined in the data provider "dataProvider".'); Test::getProvidedData(\DuplicateKeyDataProviderTest::class, 'test'); } public function testTestWithEmptyAnnotation(): void { $result = DocBlock::ofMethod(new \ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'anotherAnnotation' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); $this->assertNull($result); } public function testTestWithSimpleCase(): void { $result = DocBlock::ofMethod(new \ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWith1' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); $this->assertEquals([[1]], $result); } public function testTestWithMultiLineMultiParameterCase(): void { $result = DocBlock::ofMethod(new \ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWith1234' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); $this->assertEquals([[1, 2], [3, 4]], $result); } public function testTestWithVariousTypes(): void { $result = DocBlock::ofMethod(new \ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWithABTrueNull' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); $this->assertEquals([['ab'], [true], [null]], $result); } public function testTestWithAnnotationAfter(): void { $result = DocBlock::ofMethod(new \ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWith12AndAnotherAnnotation' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); $this->assertEquals([[1], [2]], $result); } public function testTestWithSimpleTextAfter(): void { $result = DocBlock::ofMethod(new \ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWith12AndBlahBlah' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); $this->assertEquals([[1], [2]], $result); } public function testTestWithCharacterEscape(): void { $result = DocBlock::ofMethod(new \ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWithEscapedString' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); $this->assertEquals([['"', '"']], $result); } public function testTestWithThrowsProperExceptionIfDatasetCannotBeParsed(): void { $docBlock = DocBlock::ofMethod(new \ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWithMalformedValue' ), VariousDocblockDefinedDataProvider::class); $this->expectException(Exception::class); $this->expectExceptionMessageMatches('/^The data set for the @testWith annotation cannot be parsed:/'); $docBlock->getProvidedData(); } public function testTestWithThrowsProperExceptionIfMultiLineDatasetCannotBeParsed(): void { $docBlock = DocBlock::ofMethod(new \ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWithWellFormedAndMalformedValue' ), VariousDocblockDefinedDataProvider::class); $this->expectException(Exception::class); $this->expectExceptionMessageMatches('/^The data set for the @testWith annotation cannot be parsed:/'); $docBlock->getProvidedData(); } /** * @todo Not sure what this test tests (name is misleading at least) */ public function testParseAnnotation(): void { $this->assertEquals( ['Foo', 'ほげ'], Test::getDependencies(\get_class($this), 'methodForTestParseAnnotation') ); } /** * @depends Foo * @depends ほげ * * @todo Remove fixture from test class */ public function methodForTestParseAnnotation(): void { } public function testParseAnnotationThatIsOnlyOneLine(): void { $this->assertEquals( ['Bar'], Test::getDependencies(\get_class($this), 'methodForTestParseAnnotationThatIsOnlyOneLine') ); } /** @depends Bar */ public function methodForTestParseAnnotationThatIsOnlyOneLine(): void { // TODO Remove fixture from test class } /** * @dataProvider getLinesToBeCoveredProvider * * @throws CodeCoverageException * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testGetLinesToBeCovered($test, $lines): void { if (\strpos($test, 'Namespace') === 0) { $expected = [ TEST_FILES_PATH . 'NamespaceCoveredClass.php' => $lines, ]; } elseif ($test === 'CoverageMethodNothingCoversMethod') { $expected = false; } elseif ($test === 'CoverageCoversOverridesCoversNothingTest') { $expected = [TEST_FILES_PATH . 'CoveredClass.php' => $lines]; } elseif ($test === 'CoverageNoneTest') { $expected = []; } elseif ($test === 'CoverageClassNothingTest') { $expected = false; } elseif ($test === 'CoverageMethodNothingTest') { $expected = false; } elseif ($test === 'CoverageFunctionTest') { $expected = [ TEST_FILES_PATH . 'CoveredFunction.php' => $lines, ]; } else { $expected = [TEST_FILES_PATH . 'CoveredClass.php' => $lines]; } $this->assertEquals( $expected, Test::getLinesToBeCovered( $test, 'testSomething' ) ); } public function testGetLinesToBeCovered2(): void { $this->expectException(CodeCoverageException::class); Test::getLinesToBeCovered( 'NotExistingCoveredElementTest', 'testOne' ); } public function testGetLinesToBeCovered3(): void { $this->expectException(CodeCoverageException::class); Test::getLinesToBeCovered( 'NotExistingCoveredElementTest', 'testTwo' ); } public function testGetLinesToBeCovered4(): void { $this->expectException(CodeCoverageException::class); Test::getLinesToBeCovered( 'NotExistingCoveredElementTest', 'testThree' ); } public function testGetLinesToBeCoveredSkipsNonExistentMethods(): void { $this->assertSame( [], Test::getLinesToBeCovered( 'NotExistingCoveredElementTest', 'methodDoesNotExist' ) ); } public function testTwoCoversDefaultClassAnnotationsAreNotAllowed(): void { $this->expectException(CodeCoverageException::class); Test::getLinesToBeCovered( 'CoverageTwoDefaultClassAnnotations', 'testSomething' ); } public function testFunctionParenthesesAreAllowed(): void { $this->assertSame( [TEST_FILES_PATH . 'CoveredFunction.php' => \range(10, 12)], Test::getLinesToBeCovered( 'CoverageFunctionParenthesesTest', 'testSomething' ) ); } public function testFunctionParenthesesAreAllowedWithWhitespace(): void { $this->assertSame( [TEST_FILES_PATH . 'CoveredFunction.php' => \range(10, 12)], Test::getLinesToBeCovered( 'CoverageFunctionParenthesesWhitespaceTest', 'testSomething' ) ); } public function testMethodParenthesesAreAllowed(): void { $this->assertSame( [TEST_FILES_PATH . 'CoveredClass.php' => \range(29, 33)], Test::getLinesToBeCovered( 'CoverageMethodParenthesesTest', 'testSomething' ) ); } public function testMethodParenthesesAreAllowedWithWhitespace(): void { $this->assertSame( [TEST_FILES_PATH . 'CoveredClass.php' => \range(29, 33)], Test::getLinesToBeCovered( 'CoverageMethodParenthesesWhitespaceTest', 'testSomething' ) ); } public function testNamespacedFunctionCanBeCoveredOrUsed(): void { $this->assertEquals( [ TEST_FILES_PATH . 'NamespaceCoveredFunction.php' => \range(12, 15), ], Test::getLinesToBeCovered( \CoverageNamespacedFunctionTest::class, 'testFunc' ) ); } public function getLinesToBeCoveredProvider(): array { return [ [ 'CoverageNoneTest', [], ], [ 'CoverageClassExtendedTest', \array_merge(\range(27, 44), \range(10, 25)), ], [ 'CoverageClassTest', \range(27, 44), ], [ 'CoverageMethodTest', \range(29, 33), ], [ 'CoverageMethodOneLineAnnotationTest', \range(29, 33), ], [ 'CoverageNotPrivateTest', \array_merge(\range(29, 33), \range(35, 39)), ], [ 'CoverageNotProtectedTest', \array_merge(\range(29, 33), \range(41, 43)), ], [ 'CoverageNotPublicTest', \array_merge(\range(35, 39), \range(41, 43)), ], [ 'CoveragePrivateTest', \range(41, 43), ], [ 'CoverageProtectedTest', \range(35, 39), ], [ 'CoveragePublicTest', \range(29, 33), ], [ 'CoverageFunctionTest', \range(10, 12), ], [ 'NamespaceCoverageClassExtendedTest', \array_merge(\range(29, 46), \range(12, 27)), ], [ 'NamespaceCoverageClassTest', \range(29, 46), ], [ 'NamespaceCoverageMethodTest', \range(31, 35), ], [ 'NamespaceCoverageNotPrivateTest', \array_merge(\range(31, 35), \range(37, 41)), ], [ 'NamespaceCoverageNotProtectedTest', \array_merge(\range(31, 35), \range(43, 45)), ], [ 'NamespaceCoverageNotPublicTest', \array_merge(\range(37, 41), \range(43, 45)), ], [ 'NamespaceCoveragePrivateTest', \range(43, 45), ], [ 'NamespaceCoverageProtectedTest', \range(37, 41), ], [ 'NamespaceCoveragePublicTest', \range(31, 35), ], [ 'NamespaceCoverageCoversClassTest', \array_merge(\range(43, 45), \range(37, 41), \range(31, 35), \range(24, 26), \range(19, 22), \range(14, 17)), ], [ 'NamespaceCoverageCoversClassPublicTest', \range(31, 35), ], [ 'CoverageClassNothingTest', false, ], [ 'CoverageMethodNothingTest', false, ], [ 'CoverageCoversOverridesCoversNothingTest', \range(29, 33), ], [ 'CoverageMethodNothingCoversMethod', false, ], ]; } public function testParseTestMethodAnnotationsIncorporatesTraits(): void { $result = Test::parseTestMethodAnnotations(\ParseTestMethodAnnotationsMock::class); $this->assertArrayHasKey('class', $result); $this->assertArrayHasKey('method', $result); $this->assertArrayHasKey('theClassAnnotation', $result['class']); $this->assertArrayHasKey('theTraitAnnotation', $result['class']); } public function testCoversAnnotationIncludesTraitsUsedByClass(): void { $this->assertSame( [ TEST_FILES_PATH . '3194.php' => \array_merge(\range(21, 29), \range(13, 19)), ], Test::getLinesToBeCovered( \Test3194::class, 'testOne' ) ); } /** * @dataProvider canSkipCoverageProvider */ public function testCanSkipCoverage($testCase, $expectedCanSkip): void { require_once TEST_FILES_PATH . $testCase . '.php'; $test = new $testCase('testSomething'); $coverageRequired = Test::requiresCodeCoverageDataCollection($test); $canSkipCoverage = !$coverageRequired; $this->assertEquals($expectedCanSkip, $canSkipCoverage); } public function canSkipCoverageProvider(): array { return [ ['CoverageClassTest', false], ['CoverageClassWithoutAnnotationsTest', false], ['CoverageCoversOverridesCoversNothingTest', false], ['CoverageClassNothingTest', true], ['CoverageMethodNothingTest', true], ]; } private function getRequirementsTestClassFile(): string { if (!$this->fileRequirementsTest) { $reflector = new \ReflectionClass(\RequirementsTest::class); $this->fileRequirementsTest = \realpath($reflector->getFileName()); } return $this->fileRequirementsTest; } } PK!x"Ѥ #Util/PHP/AbstractPhpProcessTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util\PHP; use PHPUnit\Framework\TestCase; /** * @small */ final class AbstractPhpProcessTest extends TestCase { /** * @var AbstractPhpProcess|\PHPUnit\Framework\MockObject\MockObject */ private $phpProcess; protected function setUp(): void { $this->phpProcess = $this->getMockForAbstractClass(AbstractPhpProcess::class); } protected function tearDown(): void { $this->phpProcess = null; } public function testShouldNotUseStderrRedirectionByDefault(): void { $this->assertFalse($this->phpProcess->useStderrRedirection()); } public function testShouldDefinedIfUseStderrRedirection(): void { $this->phpProcess->setUseStderrRedirection(true); $this->assertTrue($this->phpProcess->useStderrRedirection()); } public function testShouldDefinedIfDoNotUseStderrRedirection(): void { $this->phpProcess->setUseStderrRedirection(false); $this->assertFalse($this->phpProcess->useStderrRedirection()); } public function testShouldUseGivenSettingsToCreateCommand(): void { $settings = [ 'allow_url_fopen=1', 'auto_append_file=', 'display_errors=1', ]; $expectedCommandFormat = '%s -d %callow_url_fopen=1%c -d %cauto_append_file=%c -d %cdisplay_errors=1%c%S'; $actualCommand = $this->phpProcess->getCommand($settings); $this->assertStringMatchesFormat($expectedCommandFormat, $actualCommand); } public function testShouldRedirectStderrToStdoutWhenDefined(): void { $this->phpProcess->setUseStderrRedirection(true); $expectedCommandFormat = '%s 2>&1'; $actualCommand = $this->phpProcess->getCommand([]); $this->assertStringMatchesFormat($expectedCommandFormat, $actualCommand); } public function testShouldUseArgsToCreateCommand(): void { $this->phpProcess->setArgs('foo=bar'); $expectedCommandFormat = '%s foo=bar'; $actualCommand = $this->phpProcess->getCommand([]); $this->assertStringMatchesFormat($expectedCommandFormat, $actualCommand); } public function testShouldHaveFileToCreateCommand(): void { $expectedCommandFormat = '%s %cfile.php%c'; $actualCommand = $this->phpProcess->getCommand([], 'file.php'); $this->assertStringMatchesFormat($expectedCommandFormat, $actualCommand); } public function testStdinGetterAndSetter(): void { $this->phpProcess->setStdin('foo'); $this->assertEquals('foo', $this->phpProcess->getStdin()); } public function testArgsGetterAndSetter(): void { $this->phpProcess->setArgs('foo=bar'); $this->assertEquals('foo=bar', $this->phpProcess->getArgs()); } public function testEnvGetterAndSetter(): void { $this->phpProcess->setEnv(['foo' => 'bar']); $this->assertEquals(['foo' => 'bar'], $this->phpProcess->getEnv()); } public function testTimeoutGetterAndSetter(): void { $this->phpProcess->setTimeout(30); $this->assertEquals(30, $this->phpProcess->getTimeout()); } } PK!4r+Util/TestDox/CliTestDoxPrinterColorTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util\TestDox; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\TestCase; use PHPUnit\Util\Color; /** * @group testdox * @small */ final class CliTestDoxPrinterColorTest extends TestCase { /** * @var TestableCliTestDoxPrinter */ private $printer; protected function setUp(): void { $this->printer = new TestableCliTestDoxPrinter(null, true, \PHPUnit\TextUI\ResultPrinter::COLOR_ALWAYS); } protected function tearDown(): void { $this->printer = null; } public function testColorizesDiffInFailureMessage(): void { $raw = \implode(\PHP_EOL, ['some message', '--- Expected', '+++ Actual', '@@ @@']); $failure = new AssertionFailedError($raw); $this->printer->startTest($this); $this->printer->addFailure($this, $failure, 0); $this->printer->endTest($this, 0.001); $this->assertStringContainsString(Color::colorize('bg-red,fg-white', 'some message'), $this->printer->getBuffer()); $this->assertStringContainsString(Color::colorize('fg-red', '---' . Color::dim('·') . 'Expected'), $this->printer->getBuffer()); $this->assertStringContainsString(Color::colorize('fg-green', '+++' . Color::dim('·') . 'Actual'), $this->printer->getBuffer()); $this->assertStringContainsString(Color::colorize('fg-cyan', '@@ @@'), $this->printer->getBuffer()); } } PK!;#Util/TestDox/NamePrettifierTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util\TestDox; use PHPUnit\Framework\TestCase; /** * @group testdox * @small */ final class NamePrettifierTest extends TestCase { /** * @var NamePrettifier */ private $namePrettifier; protected function setUp(): void { $this->namePrettifier = new NamePrettifier; } protected function tearDown(): void { $this->namePrettifier = null; } public function testTitleHasSensibleDefaults(): void { $this->assertEquals('Foo', $this->namePrettifier->prettifyTestClass('FooTest')); $this->assertEquals('Foo', $this->namePrettifier->prettifyTestClass('TestFoo')); $this->assertEquals('Foo', $this->namePrettifier->prettifyTestClass('TestFooTest')); $this->assertEquals('Foo (Test\Foo)', $this->namePrettifier->prettifyTestClass('Test\FooTest')); $this->assertEquals('Foo (Tests\Foo)', $this->namePrettifier->prettifyTestClass('Tests\FooTest')); $this->assertEquals('Unnamed Tests', $this->namePrettifier->prettifyTestClass('TestTest')); } public function testTestNameIsConvertedToASentence(): void { $this->assertEquals('This is a test', $this->namePrettifier->prettifyTestMethod('testThisIsATest')); $this->assertEquals('This is a test', $this->namePrettifier->prettifyTestMethod('testThisIsATest2')); $this->assertEquals('This is a test', $this->namePrettifier->prettifyTestMethod('this_is_a_test')); $this->assertEquals('This is a test', $this->namePrettifier->prettifyTestMethod('test_this_is_a_test')); $this->assertEquals('Foo for bar is 0', $this->namePrettifier->prettifyTestMethod('testFooForBarIs0')); $this->assertEquals('Foo for baz is 1', $this->namePrettifier->prettifyTestMethod('testFooForBazIs1')); $this->assertEquals('This has a 123 in its name', $this->namePrettifier->prettifyTestMethod('testThisHasA123InItsName')); $this->assertEquals('', $this->namePrettifier->prettifyTestMethod('test')); } /** * @ticket 224 */ public function testTestNameIsNotGroupedWhenNotInSequence(): void { $this->assertEquals('Sets redirect header on 301', $this->namePrettifier->prettifyTestMethod('testSetsRedirectHeaderOn301')); $this->assertEquals('Sets redirect header on 302', $this->namePrettifier->prettifyTestMethod('testSetsRedirectHeaderOn302')); } public function testPhpDoxIgnoreDataKeys(): void { $test = new class extends TestCase { public function __construct() { parent::__construct('testAddition', [ 'augend' => 1, 'addend' => 2, 'result' => 3, ]); } public function testAddition(int $augend, int $addend, int $result): void { } public function getAnnotations(): array { return [ 'method' => [ 'testdox' => ['$augend + $addend = $result'], ], ]; } }; $this->assertEquals('1 + 2 = 3', $this->namePrettifier->prettifyTestCase($test)); } public function testPhpDoxUsesDefaultValue(): void { $test = new class extends TestCase { public function __construct() { parent::__construct('testAddition', []); } public function testAddition(int $augend = 1, int $addend = 2, int $result = 3): void { } public function getAnnotations(): array { return [ 'method' => [ 'testdox' => ['$augend + $addend = $result'], ], ]; } }; $this->assertEquals('1 + 2 = 3', $this->namePrettifier->prettifyTestCase($test)); } public function testPhpDoxArgumentExporting(): void { $test = new class extends TestCase { public function __construct() { parent::__construct('testExport', [ 'int' => 1234, 'strInt' => '1234', 'float' => 2.123, 'strFloat' => '2.123', 'string' => 'foo', 'bool' => true, 'null' => null, ]); } public function testExport($int, $strInt, $float, $strFloat, $string, $bool, $null): void { } public function getAnnotations(): array { return [ 'method' => [ 'testdox' => ['$int, $strInt, $float, $strFloat, $string, $bool, $null'], ], ]; } }; $this->assertEquals('1234, 1234, 2.123, 2.123, foo, true, NULL', $this->namePrettifier->prettifyTestCase($test)); } public function testPhpDoxReplacesLongerVariablesFirst(): void { $test = new class extends TestCase { public function __construct() { parent::__construct('testFoo', []); } public function testFoo(int $a = 1, int $ab = 2, int $abc = 3): void { } public function getAnnotations(): array { return [ 'method' => [ 'testdox' => ['$a, "$a", $a$ab, $abc, $abcd, $ab'], ], ]; } }; $this->assertEquals('1, "1", 12, 3, $abcd, 2', $this->namePrettifier->prettifyTestCase($test)); } } PK!DvII&Util/TestDox/CliTestDoxPrinterTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Util\TestDox; use Exception; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\Warning; /** * @group testdox * @small */ final class CliTestDoxPrinterTest extends TestCase { /** * @var TestableCliTestDoxPrinter */ private $printer; /** * @var TestableCliTestDoxPrinter */ private $verbosePrinter; protected function setUp(): void { $this->printer = new TestableCliTestDoxPrinter; $this->verbosePrinter = new TestableCliTestDoxPrinter(null, true); } protected function tearDown(): void { $this->printer = null; $this->verbosePrinter = null; } public function testPrintsTheClassNameOfTheTestClass(): void { $this->printer->startTest($this); $this->printer->endTest($this, 0); $this->assertStringStartsWith('Cli Test Dox Printer (PHPUnit\Util\TestDox\CliTestDoxPrinter)', $this->printer->getBuffer()); } public function testPrintsThePrettifiedMethodName(): void { $this->printer->startTest($this); $this->printer->endTest($this, 0.001); $this->assertStringContainsString('Prints the prettified method name', $this->printer->getBuffer()); } public function testPrintsCheckMarkForSuccessfulTest(): void { $this->printer->startTest($this); $this->printer->endTest($this, 0.001); $this->assertStringContainsString('✔', $this->printer->getBuffer()); } public function testDoesNotPrintAdditionalInformationForSuccessfulTest(): void { $this->printer->startTest($this); $this->printer->endTest($this, 0.001); $this->assertStringNotContainsString('│', $this->printer->getBuffer()); } public function testPrintsCrossForTestWithError(): void { $this->printer->startTest($this); $this->printer->addError($this, new Exception, 0); $this->printer->endTest($this, 0.001); $this->assertStringContainsString('✘', $this->printer->getBuffer()); } public function testPrintsAdditionalInformationForTestWithError(): void { $this->printer->startTest($this); $this->printer->addError($this, new Exception, 0); $this->printer->endTest($this, 0.001); $this->assertStringContainsString('│', $this->printer->getBuffer()); } public function testPrintsWarningTriangleForTestWithWarning(): void { $this->printer->startTest($this); $this->printer->addWarning($this, new Warning, 0); $this->printer->endTest($this, 0.001); $this->assertStringContainsString('⚠', $this->printer->getBuffer()); } public function testPrintsAdditionalInformationForTestWithWarning(): void { $this->printer->startTest($this); $this->printer->addWarning($this, new Warning, 0); $this->printer->endTest($this, 0.001); $this->assertStringContainsString('│', $this->printer->getBuffer()); } public function testPrintsCrossForTestWithFailure(): void { $this->printer->startTest($this); $this->printer->addFailure($this, new AssertionFailedError, 0); $this->printer->endTest($this, 0.001); $this->assertStringContainsString('✘', $this->printer->getBuffer()); } public function testPrintsAdditionalInformationForTestWithFailure(): void { $this->printer->startTest($this); $this->printer->addFailure($this, new AssertionFailedError, 0); $this->printer->endTest($this, 0.001); $this->assertStringContainsString('│', $this->printer->getBuffer()); } public function testPrintsEmptySetSymbolForTestWithFailure(): void { $this->printer->startTest($this); $this->printer->addIncompleteTest($this, new Exception, 0); $this->printer->endTest($this, 0.001); $this->assertStringContainsString('∅', $this->printer->getBuffer()); } public function testDoesNotPrintAdditionalInformationForIncompleteTestByDefault(): void { $this->printer->startTest($this); $this->printer->addIncompleteTest($this, new Exception, 0); $this->printer->endTest($this, 0.001); $this->assertStringNotContainsString('│', $this->printer->getBuffer()); } public function testPrintsAdditionalInformationForIncompleteTestInVerboseMode(): void { $this->verbosePrinter->startTest($this); $this->verbosePrinter->addIncompleteTest($this, new Exception('E_X_C_E_P_T_I_O_N'), 0); $this->verbosePrinter->endTest($this, 0.001); $this->assertStringContainsString('│', $this->verbosePrinter->getBuffer()); $this->assertStringContainsString('E_X_C_E_P_T_I_O_N', $this->verbosePrinter->getBuffer()); } public function testPrintsRadioactiveSymbolForRiskyTest(): void { $this->printer->startTest($this); $this->printer->addRiskyTest($this, new Exception, 0); $this->printer->endTest($this, 0.001); $this->assertStringContainsString('☢', $this->printer->getBuffer()); } public function testDoesNotPrintAdditionalInformationForRiskyTestByDefault(): void { $this->printer->startTest($this); $this->printer->addRiskyTest($this, new Exception, 0); $this->printer->endTest($this, 0.001); $this->assertStringNotContainsString('│', $this->printer->getBuffer()); } public function testPrintsAdditionalInformationForRiskyTestInVerboseMode(): void { $this->verbosePrinter->startTest($this); $this->verbosePrinter->addRiskyTest($this, new Exception, 0); $this->verbosePrinter->endTest($this, 0.001); $this->assertStringContainsString('│', $this->verbosePrinter->getBuffer()); } public function testPrintsArrowForSkippedTest(): void { $this->printer->startTest($this); $this->printer->addSkippedTest($this, new Exception, 0); $this->printer->endTest($this, 0.001); $this->assertStringContainsString('↩', $this->printer->getBuffer()); } public function testDoesNotPrintAdditionalInformationForSkippedTestByDefault(): void { $this->printer->startTest($this); $this->printer->addSkippedTest($this, new Exception, 0); $this->printer->endTest($this, 0.001); $this->assertStringNotContainsString('│', $this->printer->getBuffer()); } public function testPrintsAdditionalInformationForSkippedTestInVerboseMode(): void { $this->verbosePrinter->startTest($this); $this->verbosePrinter->addSkippedTest($this, new Exception('S_K_I_P_P_E_D'), 0); $this->verbosePrinter->endTest($this, 0.001); $this->assertStringContainsString('│', $this->verbosePrinter->getBuffer()); $this->assertStringContainsString('S_K_I_P_P_E_D', $this->verbosePrinter->getBuffer()); } } PK!dnaSetUpBeforeClassTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\SelfTest\Basic; use PHPUnit\Framework\TestCase; /** * Class SetUpBeforeClassTest * * Behaviour to test: * - setUpBeforeClass() errors do reach the user * - setUp() is not run * - how many times is setUpBeforeClass() called? * - tests are not executed * * @see https://github.com/sebastianbergmann/phpunit/issues/2145 * @see https://github.com/sebastianbergmann/phpunit/issues/3107 * @see https://github.com/sebastianbergmann/phpunit/issues/3364 */ class SetUpBeforeClassTest extends TestCase { public static function setUpBeforeClass(): void { throw new \Exception('forcing an Exception in setUpBeforeClass()'); } public function setUp(): void { throw new \Exception('setUp() should never have been run'); } public function testOne(): void { $this->assertTrue(true); } public function testTwo(): void { $this->assertTrue(true); } } PK!ppTearDownAfterClassTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\SelfTest\Basic; use PHPUnit\Framework\TestCase; /** * Class TearDownAfterClassTest * * Behaviour to test: * - tearDownAfterClass() errors do reach the user * - tests are executed * - tearDownAfterClass() should be called and reported once */ class TearDownAfterClassTest extends TestCase { public static function tearDownAfterClass(): void { throw new \Exception('forcing an Exception in tearDownAfterClass()'); } public function testOne(): void { $this->assertTrue(true); } public function testTwo(): void { $this->assertTrue(true); } } PK! ) SetUpTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\SelfTest\Basic; use PHPUnit\Framework\TestCase; /** * Class SetUpBeforeClassTest * * Behaviour to test: * - setUp() errors reacht he the user * - how many times is setUp() called? * - tests are not executed * * @see https://github.com/sebastianbergmann/phpunit/issues/3107 * @see https://github.com/sebastianbergmann/phpunit/issues/3364 */ class SetUpTest extends TestCase { public function setUp(): void { throw new \RuntimeException('throw exception in setUp'); } public function testOneWithSetUpException(): void { $this->fail(); } public function testTwoWithSetUpException(): void { $this->fail(); } } PK!<StatusTest.phpnuIw * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\SelfTest\Basic; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\Warning; /** * @covers Foo * * @uses Bar * * @testdox Test result status with and without message */ class StatusTest extends TestCase { public function testSuccess(): void { $this->createMock(\AnInterface::class); $this->assertTrue(true); } public function testFailure(): void { $this->assertTrue(false); } public function testError(): void { throw new \RuntimeException; } public function testIncomplete(): void { $this->markTestIncomplete(); } public function testSkipped(): void { $this->markTestSkipped(); } public function testRisky(): void { } public function testWarning(): void { throw new Warning; } public function testSuccessWithMessage(): void { $this->assertTrue(true, '"success with custom message"'); } public function testFailureWithMessage(): void { $this->assertTrue(false, 'failure with custom message'); } public function testErrorWithMessage(): void { throw new \RuntimeException('error with custom message'); } public function testIncompleteWithMessage(): void { $this->markTestIncomplete('incomplete with custom message'); } public function testSkippedWithMessage(): void { $this->markTestSkipped('skipped with custom message'); } public function testRiskyWithMessage(): void { // Custom messages not implemented for risky status } public function testWarningWithMessage(): void { throw new Warning('warning with custom message'); } } PK!2Vii collector.rbnu[PK!x testcase.rbnu[PK!Fӥ testsuite.rbnu[PK!error.rbnu[PK!o/X#ui/console/testrunner.rbnu[PK!9977,2ui/gtk/testrunner.rbnu[PK!`Dc"c"jui/tk/testrunner.rbnu[PK!Kui/testrunnerutilities.rbnu[PK!2>>sui/gtk2/testrunner.rbnu[PK! 000rui/testrunnermediator.rbnu[PK!\~!~!ui/fox/testrunner.rbnu[PK!&& failure.rbnu[PK! util/backtracefilter.rbnu[PK!y3 3 putil/observable.rbnu[PK!}hUUutil/procwrapper.rbnu[PK! J))}assertionfailederror.rbnu[PK!ݮ?3G3G assertions.rbnu[PK!=!n n ]^collector/dir.rbnu[PK!++ kcollector/objectspace.rbnu[PK!K4 ~ntestresult.rbnu[PK!aAmVV vautorunner.rbnu[PK!ov"lRunner/NullTestResultCacheTest.phpnuIwPK! eM##Runner/PhptTestCaseTest.phpnuIwPK!z}%Runner/DefaultTestResultCacheTest.phpnuIwPK!#Runner/ResultCacheExtensionTest.phpnuIwPK!IeBBRunner/TestResultCacheTest.phpnuIwPK! IjjRunner/TestSuiteSorterTest.phpnuIwPK!"  (FRunner/Filter/NameFilterIteratorTest.phpnuIwPK!H..! KFramework/SkippedTestCaseTest.phpnuIwPK!WW$SFramework/IncompleteTestCaseTest.phpnuIwPK!!og#6\Framework/Constraint/IsJsonTest.phpnuIwPK!0vv.9cFramework/Constraint/ClassHasAttributeTest.phpnuIwPK!{z##$ kFramework/Constraint/IsEmptyTest.phpnuIwPK!A9k'''sFramework/Constraint/FileExistsTest.phpnuIwPK!EiAA'zFramework/Constraint/IsWritableTest.phpnuIwPK!\@+~Framework/Constraint/ConstraintTestCase.phpnuIwPK!kZ <Framework/Constraint/JsonMatchesErrorMessageProviderTest.phpnuIwPK!&Framework/Constraint/LogicalOrTest.phpnuIwPK!'`1,RFramework/Constraint/DirectoryExistsTest.phpnuIwPK!,  '~Framework/Constraint/LogicalXorTest.phpnuIwPK!%" " (ߵFramework/Constraint/ArraySubsetTest.phpnuIwPK! 0YFramework/Constraint/TraversableContainsTest.phpnuIwPK!~0*Framework/Constraint/ExceptionCodeTest.phpnuIwPK!g3l-Framework/Constraint/ExceptionMessageTest.phpnuIwPK!['Framework/Constraint/LogicalAndTest.phpnuIwPK!4UU&Framework/Constraint/ExceptionTest.phpnuIwPK!)J  -Framework/Constraint/StringStartsWithTest.phpnuIwPK!߶K) Framework/Constraint/IsInstanceOfTest.phpnuIwPK!!xd d +Framework/Constraint/StringContainsTest.phpnuIwPK!d$Framework/Constraint/IsEqualTest.phpnuIwPK!Framework/Constraint/IsIdenticalTest.phpnuIwPK!%kOFramework/Constraint/SameSizeTest.phpnuIwPK!WW/fWFramework/Constraint/ObjectHasAttributeTest.phpnuIwPK!:+;;#_Framework/Constraint/IsTypeTest.phpnuIwPK!ȟ.mFramework/Constraint/RegularExpressionTest.phpnuIwPK!>î55#tFramework/Constraint/IsNullTest.phpnuIwPK!blT"{Framework/Constraint/CountTest.phpnuIwPK!N`oo(Framework/Constraint/GreaterThanTest.phpnuIwPK!5..;kFramework/Constraint/StringMatchesFormatDescriptionTest.phpnuIwPK!  +Framework/Constraint/StringEndsWithTest.phpnuIwPK!JJa@@31Framework/Constraint/ExceptionMessageRegExpTest.phpnuIwPK!|E(Framework/Constraint/ArrayHasKeyTest.phpnuIwPK!F(Framework/Constraint/JsonMatchesTest.phpnuIwPK!56%|Framework/Constraint/CallbackTest.phpnuIwPK!AA' Framework/Constraint/IsReadableTest.phpnuIwPK!Suu4 Framework/Constraint/ClassHasStaticAttributeTest.phpnuIwPK!n%WW%Framework/Constraint/LessThanTest.phpnuIwPK!SnFramework/TestCaseTest.phpnuIwPK!D'Framework/MockObject/MockObjectTest.phpnuIwPK!f&9Framework/MockObject/MockTraitTest.phpnuIwPK!&V>Framework/MockObject/MockClassTest.phpnuIwPK!7K##5DFramework/MockObject/Builder/InvocationMockerTest.phpnuIwPK!Y : iFramework/MockObject/Matcher/ConsecutiveParametersTest.phpnuIwPK!?;'sFramework/MockObject/MockMethodTest.phpnuIwPK!q((&ixFramework/MockObject/GeneratorTest.phpnuIwPK!^"/{Framework/MockObject/ConfigurableMethodTest.phpnuIwPK!,$QQ$\Framework/MockObject/MatcherTest.phpnuIwPK!I^.Framework/MockObject/InvocationHandlerTest.phpnuIwPK!^q (cFramework/MockObject/ProxyObjectTest.phpnuIwPK!^&##(?Framework/MockObject/MockBuilderTest.phpnuIwPK!hŃMM0=Framework/MockObject/ConfigurableMethodsTest.phpnuIwPK!ӐFramework/TestListenerTest.phpnuIwPK!:ГZ#Framework/TestSuiteIteratorTest.phpnuIwPK!GG?yy Framework/ConstraintTest.phpnuIwPK!.tFramework/TestSuiteTest.phpnuIwPK!?xMwwݹFramework/AssertTest.phpnuIwPK!|اFramework/TestFailureTest.phpnuIwPK!"Framework/Assert/FunctionsTest.phpnuIwPK!B4<Framework/TestBuilderTest.phpnuIwPK!Whh4Framework/Exception/InvalidArgumentExceptionTest.phpnuIwPK! O%}Framework/Exception/ExceptionTest.phpnuIwPK!j>"UFramework/ExceptionWrapperTest.phpnuIwPK!]Xٴ!8Framework/TestImplementorTest.phpnuIwPK!8M =Util/Annotation/RegistryTest.phpnuIwPK!2kq q (iUtil/XDebugFilterScriptGeneratorTest.phpnuIwPK!bb2Util/GlobalStateTest.phpnuIwPK!MrUtil/ColorTest.phpnuIwPK!͏==#3Util/ConfigurationGeneratorTest.phpnuIwPK!#hh7:Util/GetoptTest.phpnuIwPK!úPggOUtil/ConfigurationTest.phpnuIwPK!OffUtil/XmlTest.phpnuIwPK!ƴ  Util/JsonTest.phpnuIwPK!ZGA``Util/RegularExpressionTest.phpnuIwPK!/Util/TestClassTest.phpnuIwPK!x"Ѥ # Util/PHP/AbstractPhpProcessTest.phpnuIwPK!4r+ Util/TestDox/CliTestDoxPrinterColorTest.phpnuIwPK!;# Util/TestDox/NamePrettifierTest.phpnuIwPK!DvII& Util/TestDox/CliTestDoxPrinterTest.phpnuIwPK!dnad SetUpBeforeClassTest.phpnuIwPK!pp\ TearDownAfterClassTest.phpnuIwPK! )  SetUpTest.phpnuIwPK!< StatusTest.phpnuIwPKqq*