How to get caller file name in Node.js? - node.js

I have a Node class which I import in many of my projects modules Once imported into required module I create object of it and then call related methods of that object.
My question is how do I get the object caller's file name in my class file without explicitly passing so
I don't want to use module.parent.filename as it only gives the file name of parent file and not of other files. After some R&D I came to know that there is a module called stack-trace which could provide me similar functionality. But when I tried following code into my class I got the name of file itself in which the code was written and not the name of file which was calling the object of that class
const stackTrace = require('stack-trace');
var trace = stackTrace.get()
console.log(trace[0].getFileName())

The manual states, for stackTrace.get():
Returns an array of CallSite objects, where element 0 is the current call site.
You don't want the current call site, but the previous one, so you need to use trace[1].getFileName()

Related

How do I mock a a file IO so that I can override the name attribute in a unit test?

I'm trying to write a unit test mock opening a file and passing it into a function that uses it to dump a JSON object into. How do I create a fake IO object that mimics the behavior of an open file handle but uses similar attributes, specifically .name?
I've read through tons of answers on here and all of them work around the problem in various ways. I've tried mock patching builtins.open, I've tried mock patching the open being called inside my module, but the main error I keep running into is that when I try to access the fake IO object's .name attribute, I get an AttributeError:
AttributeError: 'CallbackStream' object has no attribute 'name'
So here's a simple function that writes a dictionary to disk in JSON format and takes an open file handle:
def generate(data, json_file):
# data is a dict
logging.info(f"Writing out spec file to {json_file.name}")
json.dump(data, json_file)
Here's what I've tried to unit test:
#patch("builtins.open", new_callable=mock_open())
def test_generate_json_returns_zero(self, mock_open):
mocked_file = mock_open()
mocked_file.name = "FakeFileName"
data = {'stuff': 'stuff2'}
generate(data, json_file=mocked_file)
However, that produces the AttributeError above, where I can't use json_file.name because it doesn't exist as an attribute. I thought setting it explicitly would work, but it didn't.
I can bypass the issue by using a temporary file, via `tempfile.TemporaryFile:
def test_generate_json_returns_zero(self, mock_open):
data = {'stuff': 'stuff2'}
t = TemporaryFile("w")
generate(data, json_file=t)
But that doesn't solve the actual problem, which is that I can't figure out how to mock the file handle so that I don't actually need to create a real file on disk.
I can't get past the .name not being a valid attribute. How do I mock the file object such that I could actually use the .name attribute of an IO object and still fake a json.dump() to it?
The new_callable parameter is meant to be an alternative class of Mock, so when you call:
#patch("builtins.open", new_callable=mock_open())
It patches builtins.open by replacing it with what mock_open() returns, rather than a MagicMock object, which is what you actually need, so change the line to simply:
#patch("builtins.open")
and it should work.
Your test never actually calls open, so there's no need to patch it. Just create a Mock instance with the attribute you need.
def test_generate_json_returns_zero(self):
mocked_file = Mock()
mocked_file.name = "FakeFileName"
data = {'stuff': 'stuff2'}
generate(data, json_file=mocked_file)

How do I pass the session object of a ThreadLocalODMSession to a class defined in another python file?

I hope I can explain this issue correctly.
I want to define the ThreadLocalODMSession object in one python file, and have defined several other files with the classes that represent the mongo collection. But the sample source code for ming always shows the ThreadLocalODMSession object as a local variable, that sets the session variable in the __mongometa__ subclass of the collection definition class.
In the example, the definition of WikiPage is in the same script as the definition of the ThreadLocalODMSession (called session) object, and get passed in the __mongometa__ definition.
class WikiPage(MappedClass):
class __mongometa__:
session = session
name = 'wiki_page'
I want to be able to pass the session object into the __init__ method of the WikiPage, and then have the __mongometa__ subclass set its copy of session on creation.

PHPExcel how to generate excel file via controller of Laravel 5

I use the library PHPExcel included in Classes directory.
I do a simple test in my controller.
In my controller, i placed this code:
`include(app_path().'/Classes/PHPExcel.php');`
`include(app_path().'/Classes/PHPExcel/Writer/Excel2007.php');`
Then I instantiate the object PHPExcel :
`$workbook = new PHPExcel;`
I activate the sheet on which I work (the default form), with method ->getActiveSheet().
`$sheet = $workbook->getActiveSheet();`
I filled my first cell with the method ->setCellValue().
`$sheet->setCellValue('A1','MaitrePylos');`
Finally to create the file, I need to instantiate an object writer, specific to the type of picture I want to generate.
`$writer = new PHPExcel_Writer_Excel2007($workbook);`
I give a name to my file, and save :
`$records = 'storage/app/sampleData/fichier.xlsx';`
`$writer->save($records);`
Result: I have a generated error
Class 'App\Http\Controllers\PHPExcel_Writer_Excel2007' not found
Who can help me to better organize my code and fix my error problem?
Just use the Laravel Excel Package, behind the scenes it uses the PHPExcel class.
https://github.com/Maatwebsite/Laravel-Excel

Access same object between different files from Node module

I can't find anywhere to tell me that this is completely wrong so here I go:
In my module I have two functions:
init: create the winston logger object
get: returns the object
I have several files which need to use the logger object.
In these files, I'm requiring the module, and using the get function.
I want to initialize it once. Then in other files, I want to simply require the module, get the object, and use it. Is my logic completely wrong here? I can pass it to the other modules, but I thought this would be a clean way of using the logger.
Currently in the file where I init and get the logger, I can use it just fine. Once I'm in a new file/module, the get returns undefined which leads me to believe this is incorrect.

How do i instantiate a UIMap in Class file that i have created

I"m trying to instantiate a UIMAp (the reason i need this is currenly i'm having an error thats occuring and i think its because i need to instantiate it). I've read online about how to do it but my UI maps are named the same as my cs files that are created. and i cant seem to see if i'm actually instantiating it correctly since its just a class. I have reference in the file
which is
using Microsoft.VisualStudio.TestTools.UITest.Common.UIMap;
But i dont think i'm accessing it or am i and just dont know
I tried this code HomePage MyNewUIMap = new HomePage();
but i don't believe its correct here is my folder structure
For example my folder and file structure is
--> Home (folder)
---->HomePage.uiTest(UIfile)
------->HomePage.cs (file)
----------->HomePage.Designer.cs (file)
I normally keep a utility class that does nothing but instantiate my maps. Then, I can just call MyUtility.HomePage.objectOnHomePage when I need to interact with that object, and I don't need to instantiate each map on each test class. However, the actual method for instantiating my maps is done below:
public HomePage myHomePageMap
{
get
{
if (_homePage == null)
_homePage = new HomePage();
return _homePage;
}
}
private HomePage _homePage;
I do it this way to make sure that, if I've already instantiated the map, I don't create a duplicate instance of it.

Resources