@@ -201,3 +201,66 @@ type failingExporter struct {
201201func (f * failingExporter ) Export (ctx context.Context , rm * metricdata.ResourceMetrics ) error {
202202 return fmt .Errorf ("PermissionDenied" )
203203}
204+
205+ func TestNewGRPCMetricContextWithCustomProvider (t * testing.T ) {
206+ // Create a manual reader for collecting metrics.
207+ mr := metric .NewManualReader ()
208+
209+ // Create a custom meter provider with the manual reader.
210+ customProvider := metric .NewMeterProvider (
211+ metric .WithReader (mr ),
212+ )
213+ ctx := context .Background ()
214+
215+ cfg := metricsConfig {
216+ project : "project-id" ,
217+ meterProvider : customProvider , // use custom provider
218+ disableExporter : true , // disable since this is a unit test
219+ }
220+
221+ mc , err := newGRPCMetricContext (ctx , cfg )
222+ if err != nil {
223+ t .Errorf ("newGRPCMetricContext: %v" , err )
224+ }
225+ defer mc .close ()
226+
227+ // Verify the provider in metricsContext is our custom provider.
228+ if mc .provider != customProvider {
229+ t .Errorf ("metricsContext.provider = %v, want %v" , mc .provider , customProvider )
230+ }
231+
232+ // Now we can collect metrics from the manual reader that's registered with our custom provider.
233+ rm := metricdata.ResourceMetrics {}
234+ if err := mr .Collect (ctx , & rm ); err != nil {
235+ t .Errorf ("ManualReader.Collect: %v" , err )
236+ }
237+ }
238+
239+ func TestNewGRPCMetricContextWithCustomProviderExporter (t * testing.T ) {
240+ // 1. Create a custom meter provider.
241+ mr := metric .NewManualReader ()
242+ customProvider := metric .NewMeterProvider (
243+ metric .WithReader (mr ),
244+ )
245+ // 2. Create a custom `failingExporter`.
246+ failingExp := & failingExporter {}
247+ customExporter := metric .Exporter (failingExp )
248+
249+ // 3. Create the metrics context with both the custom provider and the custom exporter.
250+ // The custom provider should take precedence and prevent the failing exporter from being used.
251+ ctx := context .Background ()
252+ cfg := metricsConfig {
253+ project : "project-id" ,
254+ meterProvider : customProvider ,
255+ customExporter : & customExporter ,
256+ }
257+
258+ mc , err := newGRPCMetricContext (ctx , cfg )
259+ if err != nil {
260+ t .Errorf ("newGRPCMetricContext: %v" , err )
261+ }
262+ // 4. Verification: The `failingExporter` should not have been used.
263+ // We expect the close to succeed, which means the failing exporter was not registered.
264+ // If the failing exporter had been used, mc.close() would likely panic or return an error.
265+ mc .close ()
266+ }
0 commit comments