Files
react-native/scripts/cocoapods/__tests__/test_utils/DirMock.rb
T
Riccardo Cipolleschi 88a1b8e18d Use FileMock and DirMock instead of Monkey Patching (#35792)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/35792

This Diff fixes a problem we have when running Ruby tests.

The previous approach was monkey-patching the Ruby File and Dir classes to override some behaviours we needed during tests. However, these classes are also used by the test runners to properly read and run the tests, therefore when the tests were failing, the stream weren't closed properly and we received the wrong errors.

This problem was also preventing us from adopting other Ruby tools like SimpleCov to compute code coverage.

## Changelog:
[internal] - refactor Ruby tests not to monkey patch Dir and File

Reviewed By: dmytrorykun

Differential Revision: D42414717

fbshipit-source-id: 879b9928da1a083ebf9c81b1f510eaa039376042
2023-01-10 06:43:39 -08:00

73 lines
2.0 KiB
Ruby
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
class DirMock < Dir
@@exist_invocation_params = []
@@mocked_existing_dirs = []
@@glob_invocation = []
@@mocked_existing_globs = {}
@@pwd = nil
# Monkey patched exists? method.
# It is used also by the test runner, so it can't start monkey patched
# To use this, invoke the `is_testing` method before starting your test.
# Remember to invoke `reset` after the test.
def self.exist?(path)
@@exist_invocation_params.push(path)
return @@mocked_existing_dirs.include?(path)
end
# Getter for the `exist_invocation_params` to check that the exist method
# is invoked with the right parameters
def self.exist_invocation_params()
return @@exist_invocation_params
end
# Set the list of dirs the test must return as existing
def self.mocked_existing_dirs(dirs)
@@mocked_existing_dirs = dirs
end
# Set what the `glob` function should return
def self.mocked_existing_globs(globs, path)
@@mocked_existing_globs[path] = globs
end
def self.glob_invocation
return @@glob_invocation
end
def self.glob(path)
@@glob_invocation.push(path)
return @@mocked_existing_globs[path] != nil ? @@mocked_existing_globs[path] : []
end
def self.remove_mocked_paths(path)
@@mocked_existing_globs = @@mocked_existing_globs.select { |k, v| v != path }
end
def self.set_pwd(pwd)
@@pwd = pwd
end
def self.pwd
if @@pwd != nil
return @@pwd
end
return pwd
end
# Resets all the settings for the File mock
def self.reset()
@@pwd = nil
@@mocked_existing_dirs = []
@@exist_invocation_params = []
@@glob_invocation = []
@@mocked_existing_globs = {}
end
end